Get New User Location in Kotlin Not working

703 Views Asked by At

Good day everyone,

I have built code from a tutorial similar to what is below. However, with the new Kotlin update it wont allow you to run fusedLocationProviderClient.requestLocationUpdates(parameters) without a permission check, which I am not sure how to implement. It should be simple though.

My problem is that in the getNewLocation() func below, the processor does not run into fusedLocationProviderClient!!.requestLocationUpdates(parameters) and the callback associated with it (NO ERROR IS SHOWN OR THIS IS NOT INDICATED WITHOUT PRINT STATEMENTS). This is a major problem because it means I cant access the users location if the initial request returned NULL.

I really hope there is someone out there that has encountered the same issue so that I can get help solving this frustrating loop-hole.

Here is the code:

class MainActivity : AppCompatActivity() {

    lateinit var fusedLocationProviderClient: FusedLocationProviderClient
    lateinit var locationRequest: LocationRequest

    //Permission id
    private var PERMISSION_ID = 1000

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //Initiate Fused Location Provider Client
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this)
        btnLocation.setOnClickListener {
            getLastLocation()
        }
    }

    //Function to get last location
    @SuppressLint("MissingPermission", "SetTextI18n")
    private fun getLastLocation() {
        if(CheckPermission()) {
            if(isLocationEnabled()) {
                fusedLocationProviderClient.lastLocation.addOnCompleteListener {task ->
                    var location = task.result
                    if(location == null) {
                        getNewLocation()
                    } else {
                        tv_location.text = "Your current coordinates are :\nLat: " + location.latitude + " ; Long: " + location.longitude +
                                "\nYour City: " + getCityName(location.latitude, location.latitude) + ", Your Country: " + getCountryName(location.latitude, location.longitude)
                    }
                }
            } else {
                Toast.makeText(this, "Please enable your location service", Toast.LENGTH_LONG).show()
            }
        } else {
            RequestPermission()
        }
    }

    @SuppressLint("MissingPermission")
    private fun getNewLocation() {
        locationRequest = LocationRequest()
        locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        locationRequest.interval = 0
        locationRequest.fastestInterval = 0
        locationRequest.numUpdates = 2
        fusedLocationProviderClient!!.requestLocationUpdates(
            locationRequest,locationCallback,Looper.myLooper()
        )
    }

    private val locationCallback = object : LocationCallback() {
        @SuppressLint("SetTextI18n")
        override fun onLocationResult(p0: LocationResult?) {
            var lastLocation = p0?.lastLocation
            if (lastLocation != null) {
                tv_location.text = "Your current coordinates are :\nLat: " + lastLocation.latitude + " ; Long: " + lastLocation.longitude +
                        "\nYour City: " + getCityName(lastLocation.latitude, lastLocation.longitude) + ", Your Country: " + getCountryName(lastLocation.latitude, lastLocation.longitude)
            }
        }
    }


    //Check user permission
    private fun CheckPermission():Boolean  {
        if(
            ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED ||
                    ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED

                ) {
            return true
        }

        return false
    }
    //Get user permission
    private fun RequestPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION), PERMISSION_ID
        )
    }
    //Check location service
    private fun isLocationEnabled():Boolean {
        var locationManager :LocationManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
        return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
    }

    private fun getCityName(lat:Double,lon:Double):String {
        var CityName = ""
        var geoCoder = Geocoder(this, Locale.getDefault())
        var Adress = geoCoder.getFromLocation(lat, lon, 1)
        CityName = Adress.get(0).locality
        return CityName
    }

    private fun getCountryName(lat:Double,lon:Double):String {
        var CountryName = ""
        var geoCoder = Geocoder(this, Locale.getDefault())
        var Adress = geoCoder.getFromLocation(lat, lon, 1)
        CountryName = Adress.get(0).countryName
        return CountryName
    }

    //Built in function to check permission result
    //Used it just for debugging
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == PERMISSION_ID) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("Debug:", "You have the permission")
            }
        }
    }
}
1

There are 1 best solutions below

3
On

you need to add these two permissions in your Androidmenifest.xml file

  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />