Search code examples
androidgeolocationlocationreverse-geocoding

How to make sure that getLastLocation().isSuccessful()


Im trying to getLastLocation(), but sometimes it is null. When that happens, I go to google maps just for a second, and return to my app and in 99% that will do. There is also one app that just returns city that you're in and it works even if my app can't getLastLocation(). I've noticed that when I use that other app, or google maps, or weather app, for a short time location icon will appear in status bar, but when I use my app that icon never appears, so I'm guessing that may be the problem?

What I need to do to assure that I get my location to be != null?

One more thing, sometimes I get my location (lat and long), but reverse geocoding goes to catch because List is empty? How to make sure it always is not empty?

The code that I use is just a copy/past from android developers.


Solution

  • If you are using Android Emulator it is expected that the location doesn't get updated unless you open the Maps App.

    To ensure you get non-null location you need to request for location updates

    You can do something like this

    @SuppressLint("MissingPermission")
        private fun getLastKnownLocation() {
    
            // get last known location from fusedLocationProviderClient returned as a task
    
            fusedLocationProviderClient.lastLocation
                .addOnSuccessListener { lastLoc ->
                    if (lastLoc != null) {
    
                        // initialize lastKnownLocation from fusedLocationProviderClient
                        lastKnownLocation = lastLoc
    
                        
    
                    } else {
    
                        // prompt user to turn on location
                        showLocationSettingDialog()
    
                        // when user turns on location trigger updates to get a location
                        fusedLocationProviderClient.requestLocationUpdates(
                            locationRequest, locationCallback, Looper.getMainLooper()
                        )
                    }
    
                    // in case of error Toast the error in a short Toast message
                }
                .addOnFailureListener {
    
                    Toast.makeText(requireActivity(), "${it.message}", Toast.LENGTH_SHORT).show()
    
                }
        }
    

    This is just a stub, you will need to handle permissions, create FusedLocationProviderClient, LocationRequest and LocationCallbackObject.

    You may also need to prompt the user to Turn on Location Settings.

    Please show us your GeoCoding code to elaborate further.