4

While it's expected that LastLocation doesn't provide a location for the first time if it's unknown. I didn't expect to see the same issue with GetCurrentLocation.

val mFusedLocationClient: FusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(mContext)
 mFusedLocationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, object: CancellationToken() {
                override fun onCanceledRequested(p0: OnTokenCanceledListener) = CancellationTokenSource().token
                override fun isCancellationRequested() = false
            }).addOnCompleteListener { it ->
                if (it.isSuccessful) {
                    val location: Location = it.result
                    // Why can this be null if it was a success?
                }
            }

How can it.isSuccessful be true and at the same time, showing the it.result (location) as null?

Houman
  • 64,245
  • 87
  • 278
  • 460

1 Answers1

0

I think, it's a behaviour of Task. When you call addOnCompleteListener, it returns a result, while addOnFailureListener listens to Task fail. In this case getCurrentLocation() tries to access/compute a current location:

This may return a cached location if a recent enough location fix exists, or may compute a fresh location. If unable to retrieve a current location fix, null will be returned.

addOnFailureListener will return an error. Maybe permissions were not granted or GPS provider didn't work, I don't know.

CoolMind
  • 26,736
  • 15
  • 188
  • 224
  • Thanks. Permissions were 100% granted though. My research shows that it could be indeed that GPS lock couldn't be acquired. But this doesn't really solve the problem. How can I retry this if it has failed the first time around though? – Houman Jan 17 '23 at 11:37
  • @Houman, sorry, I ambiguously wrote. I meant `addOnFailureListener` might return an exception in some cases (maybe permissions, hardware or Play Services error). Probably you should ask getLastLocation() or requestLocationUpdates(). – CoolMind Jan 17 '23 at 12:46
  • I made something for `requestLocationUpdates` here: https://stackoverflow.com/questions/52587361/fusedlocationclient-not-calling-onlocationresult. – CoolMind Jan 17 '23 at 12:54
  • Thank you. I checked your sample. But you are using `lastLocation` in your example instead of `getCurrentLocation` though. Unless I should be combining them, although it's not quite the same thing. LastLocation could be older than current location, that couldn't be fetched. – Houman Jan 19 '23 at 11:41
  • @Houman, thank you for a feed back. Agree with you, but currently I cannot offer more. – CoolMind Jan 19 '23 at 12:56