Method invocation may produce NullPointerException

3

I'm using geocoder to transform the address of the edit text into Longitude and Latitude. I have a problem with the app, but it does not cause any problem in the app, but it gets the error on the screen and I have to press ok every time, and it says it's because of the adresses.get (0) which gets a nullpointerException, as a little bit?

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();
    
asked by anonymous 13.11.2015 / 01:02

1 answer

4

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
    }
}
    
13.11.2015 / 01:33