The reason is that you do not handle the exception in% s. The try/catch
variable will be null and the method will continue to execute.
One 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 contain any elements. So it's always good to check if it's 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
}
}