Home > Software engineering >  Can't get last known location
Can't get last known location

Time:10-27

Not gonna lie, I'm very new in kotlin, that why I need analysis of full code.

On start it asks for permissions (don't need any more it's just test project) Pressing on the button supposed to change textView to my location

This is the code:

class MainActivity : AppCompatActivity() {

private lateinit var fusedLocationClient: FusedLocationProviderClient
private lateinit var text: TextView


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

    text = findViewById(R.id.textView)
    val button: Button = findViewById(R.id.button)
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)

    val requestMultiplePermissions = registerForActivityResult(
        ActivityResultContracts.RequestMultiplePermissions()) { permissions ->
        permissions.entries.forEach {
            Log.e("DEBUG", "${it.key} = ${it.value}")
        }
    }
    button.setOnClickListener {
        getLastKnownLocation()
    }
    requestMultiplePermissions.launch(
        arrayOf(
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION
        )
    )
}


private fun getLastKnownLocation() {

    if (ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_FINE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
            this,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        text.text = "do not grants the permission"
        return
    }

    fusedLocationClient.lastLocation
        .addOnSuccessListener { location: Location? ->
            if (location != null) {
                text.text = "My location "   location.latitude.toString()   ", "   location.longitude.toString()
            }
            else{
                text.text = "location = null"
            }
        }
} }

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

But it wrote "location = null", wats wrong here?

enter image description here

Sometimes the Device's last location is null if there is no cached location. Following the above step will ensure the last known location is not null. Re-install the App and it should show you the latitude and longitude of the device's last known location.

NB - You don't need to request for both ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION

ACCESS_FINE_LOCATIONpermission includes permissions for both NETWORK_PROVIDER and GPS_PROVIDER so you need to request only the ACCESS_FINE_LOCATION permission

  • Related