NOTE: Internet services are OFF intentionally in my phone.

Getting error at the below line:

addresses = geocoder.getFromLocation(latitude, longitude, 1)

I don't want my application to crash even if the internet service is off and want the issue to be caught in catch block. I have implemented the try/catch block, but still my app crashed by giving the below exception:

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException

is there any solution for my problem. Thanks in advance.

1

There are 1 best solutions below

1
Sadegh.t On

You should call Geocoder on a separate thread

private fun getAddress(latitude: Double, longitude: Double) {
    viewModelScope.launch {
        try {
            var addresses: List<Address>
            val deferred = this.async(Dispatchers.IO) {
                addresses = geocoder!!.getFromLocation(
                    latitude,
                    longitude,
                    1
                ) // Here 1 represent max location result to returned, by documents it recommended 1 to 5

                return@async addresses
            }
            withContext(Dispatchers.Main) {
                val data = deferred.await()
                showAddress(data)
            }

        } catch (e: Exception) {
            Log.e("location", e.message!!)
        }
    }
}

Retrieve address:

 private fun showAddress(addresses: List<Address>) {
    val address = addresses[0]
        .getAddressLine(0) // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()

    val city = addresses[0].locality
    val state = addresses[0].adminArea
    val country = addresses[0].countryName
    val postalCode = addresses[0].postalCode
    val knownName = addresses[0].featureName // Only if available else return NULL

}