Error handling in the Google maps Android API

0

I am making a register of people with address to show on the map where a person lives. When I type the correct address everything works normally, but when I get the error, which is not valid for Google Maps , the app closes.

@Override
public void onResume() {
    super.onResume();

    FragmentActivity context = getActivity();
    LatLng local = new Localizador(context).getCoordenada("R. Eurita, 47 - Santa Teresa - Belo Horizonte - MG");
    centralizaNo(local);

    AlunoDAO dao = new AlunoDAO(context);
    List<Aluno> alunos = dao.getLista();

    for (Aluno aluno : alunos) {

        GoogleMap map = getMap();

        LatLng localAluno = new Localizador(context).getCoordenada(aluno.getEndereco());

        MarkerOptions options = new MarkerOptions().title(aluno.getNome()).position(localAluno);
        map.addMarker(options );

    }

    dao.close();
}

public void centralizaNo(LatLng local) {
    GoogleMap map = getMap();
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(local , 15);
    map.animateCamera(update );
}

I would like some help to handle the error and if the person enters an invalid address does not appear on the map to flow normally.

public class Localizador {
    private Context context;

    public Localizador(Context context){
        this.context = context;
    }

    public LatLng getCoordenada(String endereco) {
        Geocoder geocoder = new Geocoder(context);

        try {
            List<Address> enderecos = geocoder.getFromLocationName(endereco, 1);
            if (!enderecos.isEmpty()){

                Address enderecoLocalizado = enderecos.get(0);
                double latitude = enderecoLocalizado.getLatitude();
                double longitude = enderecoLocalizado.getLongitude();

                return new LatLng(latitude, longitude);
            } else {
                return null;
            }
        } catch (IOException e) {
            return null;
        }
    }
}
    
asked by anonymous 15.05.2015 / 14:37

1 answer

2

Since your getCoordenada method already returns a null value if you do not find the address you entered, you only need to do a check before using a coordinate to define a location, no matter where it is.

So more or less:

Localizador localizador = new Localizador(context);
LatLng localAluno = localizador.getCoordenada(aluno.getEndereco());

if (localAluno != null) {
    MarkerOptions options = new MarkerOptions().title(aluno.getNome()).position(localAluno);
    map.addMarker(options);
}

So you prevent any exception that actually does occur if the position set with position() is null.

    
15.05.2015 / 14:48