MapFragment or MapView getMap() returns null on Lollipop

爱⌒轻易说出口 提交于 2019-11-27 02:13:21

问题


I've been using Google Maps API v2 for a long time on Android 4.x versions without a problem. Now I installed latest Lollipop build on my Nexus devices (5 and 7) trying to materialize the app.

I'd like to point out that everything is ok on KitKiat and the problem I'm describing is poping up only on Lollipop.

In my XML source code I'm using MapFragment (Google Play Services library version 6.1.11).

<fragment android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:name="com.google.android.gms.maps.MapFragment"/>

In Java code I'm overriding OnPause() method to reach map:

GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

At this line it throws NullPointerException. In debugger app is able to find fragment, however it's not able to return GoogleMap. I've also tried to use MapView. It also throws null. The weirdest thing for me is that map loads without a problem on app itself but in code I cant reach it to work with it.


回答1:


I had exactly the same problem but this is what worked for me:

Replace this...

GoogleMap map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

with this...

GoogleMap map = getMapFragment().getMap();

then slip this bad boy in and give it a whirl...

private MapFragment getMapFragment() {
    FragmentManager fm = null;

    Log.d(TAG, "sdk: " + Build.VERSION.SDK_INT);
    Log.d(TAG, "release: " + Build.VERSION.RELEASE);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Log.d(TAG, "using getFragmentManager");
        fm = getFragmentManager();
    } else {
        Log.d(TAG, "using getChildFragmentManager");
        fm = getChildFragmentManager();
    }

    return (MapFragment) fm.findFragmentById(R.id.map);
}



回答2:


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;
         }
    });



回答3:


It looks like this might be an issue with a targetSdkVersion of 21: https://code.google.com/p/android-developer-preview/issues/detail?id=1947

However, switching to getChildFragmentManager() worked for me:

findFragmentById for SupportMapFragment returns null in Android Studio




回答4:


Have you tried isGooglePlayServicesAvailable to check why its returning null? null has many reasons on getmap, try using this to check why its giving null



来源:https://stackoverflow.com/questions/26592889/mapfragment-or-mapview-getmap-returns-null-on-lollipop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!