javaandroidgoogle-mapsnullpointerexceptionmapfragment

NullPointerException : Attempt to invoke virtual method 'void com.google.android.gms.maps.MapFragment.getMapAsync


I'm using com.google.android.gms:play-services-maps:11.0.2 version of Google Map Service. When trying to call the below, I get the following error:

java.lang.NullPointerException: Attempt to invoke virtual method
void

com.google.android.gms.maps.MapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference

Below is my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

}

Solution

  • Looks like you are using SupportMapFragment instead of MapFragment.

    Change this line:

    mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);

    To this:

    mapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(R.id.map);