Error handling in Google maps Android API

Asked

Viewed 205 times

0

I’m running a register of people with addresses to show on the map where a person lives. When I type the correct address everything works normally, but when I error the address, it is not valid for the 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 );
}

Wanted help handling the bug 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;
        }
    }
}

1 answer

2


Like your method getCoordenada already returns a null value if you do not find the given address, just do a check before using a coordinate to define a location, regardless of where it is.

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);
}

Thus you prevent any exception that actually occurs if the position defined with position() be void.

  • Thanks for the help, it worked!

Browser other questions tagged

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