Method Invocation may Produce Nullpointerexception

Asked

Viewed 533 times

4

I’m using geocoder to turn the Edit text address into Longitude and Latitude. Then he’s doing it right and saving in the bank the lat and lng, but he gives an Exception that does not cause any problem in the app, but keeps giving the error on the screen and I have to press ok every time, and he says it is because of the adresses.get(0) that is giving a nullpointerException, as adjusted?

Geocoder geocoder = new Geocoder(this, Locale.getDefault());
    List<Address> addresses = null;
    try {
        addresses = geocoder.getFromLocationName(stringLocal, 1);
    } catch (IOException e) {
        e.printStackTrace();
    }

    Address address = addresses.get(0);
    double longitude = address.getLongitude();
    double latitude = address.getLatitude();

1 answer

4

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
    }
}
  • 1

    It worked, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.