Skip to content Skip to sidebar Skip to footer

Creating Google Maps V2 In A Fragment Using Navigation Drawer

I am trying to create a map in a Fragment but keep getting this error: java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.GoogleMap com.g

Solution 1:

This is an answer an a response to this comment

So basically, folks use SupportMapFragment#getMap() to get the GoogleMap object for quite a long time. And there are too many questions/answers/discussions/work-arounds/tricks to get rid of the NPE it may produce.

And finally, Google made a right step which you can see here: deprecate that getMap() method and add getMapAsync() instead

So your app/fragment which contains a MapView/MapFragment must implement the com.google.android.gms.maps.OnMapReadyCallback interface and override its onMapReady(GoogleMap map) where you get the Map object. The idea is that GoogleMap object needs time to be initialized, so if you call the deprecated getMap() method, what you get may be a NULL object. It causes NPE. So the right way is to get it a-synchronically and setup a callback to retrieve the non-null object.

I created a github repo: Google Map Practice to help you see how you can easily implement that, and go for the better way. I'm really surprised that Android Studio by default create a Google Map Activity (which is DefaultMapsActivity in the repo) with the deprecated getMap() usage. It maybe because they didn't update their legacy template for a long time. But since Google notice you about new API, please take a look. Cheer!

P/S: If you want to try my repo, don't forget to setup your Google Api Key in /app/src/release/res/values/google_maps_api.xml as well as /app/src/debug/res/values/google_maps_api.xml

Solution 2:

You have did small mistake i think, Check out OnResume Method:

@Override
public void onResume() {
    super.onResume();
    initilizeMap();
    if (googleMap != null) {

    }
}

Change this to,

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

    if (googleMap != null) {
        initilizeMap();
    }
}

Post a Comment for "Creating Google Maps V2 In A Fragment Using Navigation Drawer"