Search code examples
androidgoogle-maps

Why does getMapCapabilities cause a NullPointerException when called in onMapReady?


I'm checking whether I can use AdvancedMarkers on a given device by calling getMapCapabilities.

@Override
public void onMapReady(@NonNull GoogleMap googleMap) {
    MapCapabilities mapCapabilities = googleMap.getMapCapabilities();

However, this crashes every time with a NullPointerException:

java.lang.NullPointerException: null reference
at com.google.android.gms.common.internal.Preconditions.checkNotNull(com.google.android.gms:play-services-basement@@18.1.0:1)
at com.google.android.gms.maps.model.MapCapabilities.<init>(com.google.android.gms:play-services-maps@@18.2.0:1)
at com.google.android.gms.maps.GoogleMap.getMapCapabilities(com.google.android.gms:play-services-maps@@18.2.0:1)

The map isn't null so I'm confused what is failing the checkNotNull condition.

I am running on a virtual device but I still wouldn't have expected it to crash.


Solution

  • For some reason, moving getMapCapabilities() out of onMapReady caused it to work okay. I'm not entirely sure why, as the whole point of onMapReady is that the map is... ready.

    I also found that it's not possible to chain map.getMapCabilities().isAdvancedMarkersAvailable() without the same error occurring. I had to first get the MapCababilities, then separately check if AdvancedMarkers are available.

    All in all, it's a bit of a weird problem, and it may well be linked to the fact that it's running on an emulator. The documentation doesn't really shed any light on this.