I am trying to access the location information of my Android phone using an app and I can not appear to get the current location. My code is as follows:
fusedLocationClient = LocationServices.getFusedLocationProviderClient(requireActivity())
val location_button = view.findViewById<ImageButton>(R.id.get_location)
location_button.setOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(requireActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_DENIED || ContextCompat.checkSelfPermission(requireActivity(), android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_DENIED) {
val permission = arrayOf(android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION)
requestPermissions(permission, LOC_PERMISSION_CODE)
}
else {
//permission already granted
fusedLocationClient.lastLocation
.addOnSuccessListener { location ->
// Got last known location. In some rare situations this can be null.
val latitude = location?.latitude
val longitude = location?.longitude
println(latitude)
println(longitude)
}
.addOnFailureListener {
Toast.makeText(requireActivity(), "Failed on getting current location",
Toast.LENGTH_SHORT).show()
}
}
}
else {
fusedLocationClient.lastLocation
.addOnSuccessListener { location : Location? ->
// Got last known location. In some rare situations this can be null.
println(location)
}
}
Upon the first run, I successfully get prompted to grant location access and I do so. Then it calls for the lastLocation which always equals null. If I run the app again, I will get sent to the first else block where I print out latitude and longitude but they both always print null even though I have successfully granted location access, and called for the last location.
I was beginning to think maybe last location does not work if a location has never been saved and I see there is a function from the FusedLocationProviderClient class named "getCurrentLocation()" but I can not figure out how to call it. Am I missing something?