The cause is that you do not treat the exception in the s I try/catch
. The variable addresses
will be null and the method will continue running.
A possible correct encoding for this code would be:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(stringLocal, 1);
} catch (IOException e) {
//mostra mensagem de erro
return; //sai do método já que não consegue calcular
}
Address address = addresses.get(0);
double longitude = address.getLongitude();
double latitude = address.getLatitude();
Another possibility would be:
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocationName(stringLocal, 1);
Address address = addresses.get(0);
double longitude = address.getLongitude();
double latitude = address.getLatitude();
} catch (IOException e) {
//mostra mensagem de erro
return; //sai do método já que não consegue calcular
}
Do not forget that an error can also occur if the list does not bring any element. So it is always good to check that it is not empty. Example:
public void mostrarCoordenadas() {
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geocoder.getFromLocationName(stringLocal, 1);
if (!addresses.isEmpty()) {
Address address = addresses.get(0);
double longitude = address.getLongitude();
double latitude = address.getLatitude();
//exibe latitude e longitude
} else {
//mostra erro amigável
}
} catch (IOException e) {
//mostra erro amigável
}
}
It worked, thank you very much!
– Biellx