6

I'm trying to get a map from a SupportMapFragment but it returns null. From what I read this could be because the fragment is not yet fully displayed and therefore no map exists?! I tried fixing it using executePendingTransactions() but with no success so far.

Any ideas how to fix it?

Here is the code

private GoogleMap map;
private SupportMapFragment mapFragment;
@Override
public void onCreate( Bundle savedInstanceState ) {

    //...
    super.onCreate( savedInstanceState ); 
    setContentView( R.layout.screen_mission2 );
    GoogleMapOptions mapOptions = new GoogleMapOptions();

    mapOptions.mapType(GoogleMap.MAP_TYPE_NORMAL)
        .compassEnabled(true)
        .rotateGesturesEnabled(false)
        .tiltGesturesEnabled(false);

    android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
    android.support.v4.app.FragmentManager.enableDebugLogging(true);
    mapFragment = SupportMapFragment.newInstance(mapOptions);
    FragmentTransaction fragmentTransaction = myFragmentManager.beginTransaction();
    fragmentTransaction.add(R.id.mapFragment, mapFragment);
    fragmentTransaction.commit();
    myFragmentManager.executePendingTransactions();

    if(mapFragment == null) Base.log("mapFragment==null");
    if(map==null){
        map = mapFragment.getMap();
        Base.log("map should have been initialized");
        if(map==null) Base.log("map still null");
    }
}

And the layout file:

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

It returns the following log

V/FragmentManager(24224): add: SupportMapFragment{4078c4b8 id=0x7f06003d}
V/FragmentManager(24224): Allocated fragment index SupportMapFragment{4078c4b8 #1 id=0x7f06003d}
V/FragmentManager(24224): moveto CREATED: SupportMapFragment{4078c4b8 #1 id=0x7f06003d}
D/EMR     (24224): map should have been initialized
D/EMR     (24224): map still null
4

3 回答 3

14

尝试将所有引用您的代码移动GoogleMaponStart()or onResume()。地图片段中的地图直到片段通过onCreateView链接)之后才被实例化,这发生在父活动通过之后onCreate()。另外,你需要检查你GoogleMapnull,因为如果没有安装谷歌播放服务,或者地图由于其他原因不可用,它将是null.

于 2013-12-23T16:50:37.090 回答
1

根据我的阅读,这可能是因为该片段尚未完全显示,因此不存在地图?

正确的。

任何想法如何解决它?

实际上使用布局文件,通过调用setContentView(),并摆脱所有的FragmentTransaction东西。然后,您可以检索已经创建的SupportMapFragment并使用它:

setContentView(R.layout.activity_main);

SupportMapFragment mapFrag=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.mapFragment);
于 2013-07-21T11:15:43.010 回答
1

您必须按照Google API中的说明实现OnMapReadyCallback、定义public void onMapReady(GoogleMap map)并使用它来操作片段

于 2015-11-21T09:50:55.137 回答