GPS on Android - Map = null

2

I'm making an app for people with addresses. Every time I open the map by setting the initial location with the cell phone's GPS, the app hangs and closes.

[UPDATE] In analysis to the code I noticed that the variable "map" is receiving null value, causing hard close in the application. I need help identifying the error.

Follow the 4 classes:

public class MapaFragment extends SupportMapFragment {

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

    FragmentActivity context = getActivity();

    AlunoDAO dao = new AlunoDAO(context);
    List<Aluno> alunos = dao.getLista();
    for (Aluno aluno : alunos) {

        GoogleMap map = getMap();

        Localizador localizador = new Localizador(context);
        LatLng localAluno = localizador.getCoordenada(aluno.getRua() + "," + aluno.getNumero() + "-" + aluno.getBairro() + "," + aluno.getCidade());

        if (localAluno != null) {
            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 );
}
}

Finder:

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

Show nearby students:

public class MostraAlunosProximos extends FragmentActivity{

private AtualizadorDePosicao atualizador;

@Override
protected void onCreate(Bundle arg0) {
    super.onCreate(arg0);
    setContentView(R.layout.map_layout);

    FragmentManager manager = getSupportFragmentManager();

    FragmentTransaction transaction = manager.beginTransaction();

    MapaFragment mapaFragment = new MapaFragment();
    transaction.replace(R.id.mapa, new MapaFragment());
    transaction.commit();

    atualizador = new AtualizadorDePosicao(this, mapaFragment);

}

@Override
protected void onDestroy() {
    super.onDestroy();

    atualizador.cancelar();
}
}

Position updater:

public class AtualizadorDePosicao implements LocationListener {

private LocationManager locationManager;
private MapaFragment mapa;

public AtualizadorDePosicao(Activity activity, MapaFragment mapa) {
    this.mapa = mapa;

    locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);

    String provider = LocationManager.GPS_PROVIDER;
    long tempoMinimo = 0;
    float distanciaMinima = 0;

    locationManager.requestLocationUpdates(provider, tempoMinimo, distanciaMinima, this);
}

public void cancelar() {
    locationManager.removeUpdates(this);
}

@Override
public void onLocationChanged(Location novaLocalizacao) {
    double latitude = novaLocalizacao.getLatitude();
    double longitude = novaLocalizacao.getLongitude();

    LatLng local = new LatLng(latitude, longitude);

    mapa.centralizaNo(local);
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onProviderDisabled(String provider) {
}
}

[UPDATE] Logcat error trying to open map:

05-20 16:23:34.893  15954-15954/cadastro.grupotmt.com.br.cadastrotmt E/SysUtils﹕ ApplicationContext is null in ApplicationStatus
05-20 16:23:40.276  15954-15954/cadastro.grupotmt.com.br.cadastrotmt E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: cadastro.grupotmt.com.br.cadastrotmt, PID: 15954
java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.animateCamera(com.google.android.gms.maps.CameraUpdate)' on a null object reference
        at cadastro.grupotmt.com.br.cadastrotmt.MapaFragment.centralizaNo(MapaFragment.java:46)
        at cadastro.grupotmt.com.br.cadastrotmt.AtualizadorDePosicao.onLocationChanged(AtualizadorDePosicao.java:43)
        at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:281)
        at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:210)
        at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:226)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5312)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
    
asked by anonymous 20.05.2015 / 21:12

1 answer

2

Your object map you only need to get it once in this class, you do not need to fetch it every time, every iteration of students, and so on. Perhaps because it's out of context, when you run the centralizaNo method out of this fragment you're missing out on its reference.

I've optimized one part of your code, see if it solves something:

public class MapaFragment extends SupportMapFragment {
    private Context context;
    private GoogleMap map;

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

        context = getActivity();

        map = getMap();

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

        Localizador localizador = new Localizador(context);

        for (Aluno aluno : alunos) {
            LatLng localAluno = localizador.getCoordenada(aluno.getRua() + "," + aluno.getNumero() + "-" + aluno.getBairro() + "," + aluno.getCidade());

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

        dao.close();
    }

    public void centralizaNo(LatLng local) {
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(local , 15);
        if (update != null)
            map.animateCamera(update);
    }
}
    
20.05.2015 / 22:20