Search code examples
androidandroid-mapssupportmapfragment

Android 4.2 getSupportFragmentManager().getMap() returns null


I've met this problem on Android 4.2. I have three devices, one has 4.1.1 on it, a two another have 4.2. On 4.1 phone getSupportFragmentManager().getMap() returns a map, I can see it, I can find my location and so on. But on two another it returns null.

Here's my code on map setup:

mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(false);
mMap.setOnMyLocationChangeListener(this);

On 4.2 each of last three lines throws NullPointerException. On 4.1 all of them work.

I can't find, why it happens.

PS: Google maps works great on 4.2. And "My location" button works too. PS2: In the settings "Access my location", "GPS Sattelites" and "Wi-Fi & mobile network location" are turned on.


Solution

  • Google now made a more convenient way to get the map using the following method

    myMapFragment.getMapAsync(new OnMapReadyCallback) {
         @Override
         public void onMapReady(GoogleMap googleMap) {
             myMap = googleMap;
             // Put your code here
    
         }
    });