Nullpointerexception error in setMyLocationEnabled()

Asked

Viewed 94 times

1

I am developing an app that has as its main function to capture the user’s location. I already made a code but it error, I do not know if it is complete, I did following examples of the internet:

Code:

private GoogleMap mMap;

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    MapFragment fragment = (MapFragment)getChildFragmentManager().findFragmentById(R.id.map);
    fragment.getMapAsync(this);

    return rootView;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap.setMyLocationEnabled(true);


}

Error in runtime:

Process: com.compscitutorials.basigarcia.navigationdrawervideotutorial, PID: 16457
   java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference
       at br.com.projeto.caminhossembarreiras.MainFragment.onMapReady(MainFragment.java:37)
       at com.google.android.gms.maps.MapFragment$zza$1.zza(Unknown Source)
       at com.google.android.gms.maps.internal.zzl$zza.onTransact(Unknown Source)
       at android.os.Binder.transact(Binder.java:387)
       at com.google.android.gms.maps.internal.v$a$a.a(:com.google.android.gms.alldynamite:82)
       at maps.ei.bu$6.run(Unknown Source)
       at android.os.Handler.handleCallback(Handler.java:746)
       at android.os.Handler.dispatchMessage(Handler.java:95)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5443)
       at java.lang.reflect.Method.invoke(Native Method)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

Line error:

 mMap.setMyLocationEnabled(true);
  • 1

    https://github.com/googlesamples/android-play-location

1 answer

0

The method onMapReady returns the map loaded as parameter (googleMap).

You need to pass the reference to the mMap!

Try the following:

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap  = googleMap;
    mMap.setMyLocationEnabled(true);
}

Browser other questions tagged

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