I'm having problems similar to the one at this question. Unlike in that question though, I have the correct set up (API keys are specified in the manifest, maps & places APIs enabled on the Google console) because the code works most of the time:
private fun performPlaceDetection() {
// use the Places API.
try {
val placeResult = placeDetectionClient.getCurrentPlace(null)
placeResult.addOnCompleteListener({ task ->
val likelyPlaces = task.result
for (placeLikelihood in likelyPlaces) {
Timber.d( String.format("Place '%s' has likelihood: %g",
placeLikelihood.place.name,
placeLikelihood.likelihood))
}
likelyPlaces.release()
})
} catch (e: SecurityException) {
Timber.d("error fetching current place. permissions?: " + e.message)
e.printStackTrace()
} catch (e: RuntimeExecutionException) {
Timber.d("error fetching current place: " + e.message)
e.printStackTrace()
}
}
The code occasionally fails with this:
com.google.android.gms.tasks.RuntimeExecutionException: com.google.android.gms.common.api.ApiException: 13: ERROR
or when I turn off network connectivity, I get this error:
com.google.android.gms.tasks.RuntimeExecutionException: com.google.android.gms.common.api.ApiException: 7: NETWORK_ERROR
What stumps me is that in either case, the exception (RunTimeExecutionException
) is not caught. I understand that in Kotlin, all exceptions are unchecked but I'd imagine they'd be caught if there was an error. Any clues?
UPDATE:
Looks like catching the exception inside the OnCompleteListener
works, whereas the outer one is not caught:
try {
val placeResult = placeDetectionClient.getCurrentPlace(null)
placeResult.addOnCompleteListener({ task ->
try {
val likelyPlaces = task.result
for (placeLikelihood in likelyPlaces) {
Timber.d( String.format("Place '%s' has likelihood: %g",
placeLikelihood.place.name,
placeLikelihood.likelihood))
}
likelyPlaces.release()
} catch (e: Exception) {
Timber.d("inner exception: $e")
}
})
} catch(e: Exception) {
Timber.d("outer exception: " + e::class.qualifiedName)
}
I'm not sure why the inner exception is caught. My guess is that it's because placeDetectionClient.getCurrentPlace()
runs asynchronously (and that the errors are thrown by the Places API from a separate thread) but I'm not sure (performPlaceDetection()
is called from the MainActivity of an Android app). Would appreciate some input on this one.