Map variable only gets null value

Asked

Viewed 114 times

1

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.

While analyzing the code I realized that the variable map is receiving null value, causing hard close in the app. I need help identifying and fixing the bug.

  public class MapaFragment extends SupportMapFragment {
    private Context context;
    private GoogleMap map;
    private AlunoDAO dao;
    private Localizador localizador;


    @Override
    public void onResume() {
        super.onResume();        
        context = getActivity();   

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                map = googleMap;
                addMarkers(map);
            }
        });
    }

    public void centralizaNo(LatLng local) {
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(local, 17);
        if (update != null) {
            map.animateCamera(update);
        }
    }

    private void addMarkers(GoogleMap map){
       dao = new AlunoDAO(context);
        List<Aluno> alunos = dao.getLista();

        localizador = new Localizador(getActivity());

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

}

Logcat:

05-25 16:15:45.787    2425-2425/cadastro.grupotmt.com.br.cadastrotmt E/SysUtils﹕ ApplicationContext is null in ApplicationStatus
05-25 16:15:51.523    2425-2425/cadastro.grupotmt.com.br.cadastrotmt E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: cadastro.grupotmt.com.br.cadastrotmt, PID: 2425
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:49)
        at cadastro.grupotmt.com.br.cadastrotmt.AtualizadorDePosicao.onLocationChanged(AtualizadorDePosicao.java:42)
        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)

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 = 20000;
    float distanciaMinima = 20;

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

Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/background_material_light"
android:name="com.google.android.gms.maps.MapFragment">

<WebView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/mapa">
</WebView>
</LinearLayout>
  • What is null is map. You must be calling the method centralizaNo() before a value is assigned to it. Try to do the @Override of the method onActivityCreated() and put the line there map = getMap();.

  • I will edit the post with the class I call the method centralizaNo(). You can make an example of onActivityCreated() for me to have a basis?

  • 1

    @Felipemiranda advise you to use the Try-catch in your code for the application not to close and in strategic points put a Logcat (Log.i("Metodo Tal","entrou no método"); , this way you will know where the error is happening... Another way could be Debug, but this business never works with me, so it’s up to you to decide!

2 answers

2

The problem seems to be because the 'Googlemap' object has not yet been inserted into the 'map' variable. Try something like that:

        public class MapaFragment extends SupportMapFragment {
        private Context context;
        private GoogleMap map;
        private AlunoDAO dao;
        private Localizador localizador;


        @Override
        public void onResume() {
            super.onResume();        
            context = getActivity();   

        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
            getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(GoogleMap googleMap) {
                    map = googleMap;
                    addMarkers(map);
                }
            });
        }

        public void centralizaNo(LatLng local) {
            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(local, 17);
            if (update != null) {
                map.animateCamera(update);
            }
        }

        private void addMarkers(GoogleMap map){
           dao = new AlunoDAO(context);
            List<Aluno> alunos = dao.getLista();

            localizador = new Localizador(getActivity());

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

 }
  • Thanks for the help, but it keeps crashing when I open the map. I edited my post with logcat. Nothing seems to solve the problem. Do you have any other solution?

1

Reading the documentation to Supportmapfragment I see that the method getMap() is considered obsolete and that the method getMapAsync()

So add to your class Mapafragment the following method:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    getMatAsync(new OnMapReadyCallback(){
        @Override
        public void onMapReady (GoogleMap googleMap){
            map = googleMap;
        }
    });
}
  • I didn’t know that. Even replacing the method getMap(), when I run the application it locks as soon as I open the map.

  • I edited the post with the new class and layout I’m using.

  • Do you have any possible solution?

  • In which Activity method you create the class instance Updater?

  • Within Mapafragment?

  • In what place? In the code posted does not appear. What error is giving now?

  • I just noticed that I didn’t put it anywhere. Would you be able to edit your reply? I edited my post with the logcat current.

  • The mistake now is in onResume() from Mapfragment. It seems that my solution has made things worse.

  • you have some solution?

  • I can’t think of anything.

Show 5 more comments

Browser other questions tagged

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