GPS on Android - Map=null

Asked

Viewed 165 times

2

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

[UPDATE] When analyzing the code I realized that the variable "map" is receiving null value, causing hard close in the application. I need help to identify the error.

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

Locator:

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 refresher:

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 while 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)
  • 2

    Some mistake in the logcat to show us?

  • edited the post with the bugs.

  • 1

    The log indicates that the error is in the method centralizaNo, but I have not located in your code where you call this method.

  • In the Updater class I call him on onLocationChanged

  • Paul, I edited the class where I call the centralized method

1 answer

2

Your object map you only need to get it once in this class, no need to search for it every time, every iteration of students and etc. Maybe because it is out of context, when you run the method centralizaNo out of this Fragment you’re missing his reference.

I optimized a part of your code, see if it solves anything:

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);
    }
}
  • Paulo, thanks for the touch. I will treat all possible errors, but I’m still stuck in the GPS. I made the aforementioned changes and it didn’t work.

  • Is the error still the same? Can you verify if map is void?

  • Yes, it remains the same. It opens the map, the GPS icon appears in the task bar of the mobile phone but hangs.

  • If map were null it would not open. Correct?

  • You can use the debug of your IDE and stop at this method to identify if any of these variables are null?

  • Yes. I just looked and map=null

  • Paul, can you help me?

  • Look now, I’ve edited my answer.

  • Do you believe that map is still getting null? When it arrives at animateCamera it hangs.

Show 6 more comments

Browser other questions tagged

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