androidgoogle-mapsandroid-studionullpointerexceptionsupportmapfragment

onMapReady not being called: Google Map in FrgmentActivity: Android Studio


I have a FragmentActivity in which i am trying to load the google map. And it implements OnMapReadyCallBack and when i try to inflate the map i get the mapFragment object but the app crashes after getMapAsync is called. Below is my code:

public class MapActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap googleMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_map);

    initializeMap();
    }

    private void initializeMap() {
        if (googleMap == null) {
            SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
            if(mapFragment!=null){
                mapFragment.getMapAsync(MapActivity.this);
            }

            // check if map is created successfully or not
            if (null== googleMap) {
                Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
            }
        }
    }

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

I tried to degug and i noticed that i am getting the mapFragment object but it never reaches the onMapReady method which makes my googleMap object to be null and the app crashes when any method pertaining to googleMap(e.g. setOnCameraChangeListener) is being called. I have gone through the documentation page but it doesn't seem to work in my project.

Is there something i might be missing in my project? How should i overcome this error and stop the app to crash.

TIA

EDIT 1:

Below is my map fragment in xml file

<fragment
  android:id="@+id/map"
  class="com.google.android.gms.maps.SupportMapFragment"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MapsActivity"
  android:name="com.google.android.gms.maps.SupportMapFragment"/>

Solution

  • The hint is getMapAsync (asynchronous).

    onMapReady is not called straight away, meaning that googleMap won't be set until the method is called.

    edit: Make sure you aren't doing methods call on googleMap before it is set the map value, i.e. add a check if it is null before running a method on it. Also add the @Nullable annotation to private GoogleMap googleMap; it will aid in development as Android studio will alert you if you are missing a null check.