在谷歌地图V2 ... fragment.getMap()返回null

时间:2013-02-16 11:45:42

标签: java android google-maps

我无法得到地图!我能得到的只是空。

这是代码。

       public class MainActivity extends FragmentActivity {

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

        SupportMapFragment fragment = new SupportMapFragment();
        getSupportFragmentManager().beginTransaction()
                .add(android.R.id.content, fragment).commit();


       GoogleMap map;
        map = fragment.getMap();
             //here i cant access this snippet because map = null 
        if(map!=null){
        UiSettings mm = map.getUiSettings();
        map.setMyLocationEnabled(true);
          } }
           }

清单:

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.anywhere_reminder"
android:versionCode="1"
android:versionName="1.0" >

    <uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" />
    <uses-feature
    android:glEsVersion="0x00020000"
     android:required="true"/>

   <permission
    android:name="com.example.anywhere_reminder.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

 <uses-permission android:name="com.example.anywhere_reminder.permission.MAPS_RECEIVE" />
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 <uses-permission   android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"     />

    <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity android:name="com.google.android.gms.BuildConfig" />
    <activity
        android:name="com.example.anywhere_reminder.MainActivity"
        android:label="@string/app_name" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        </activity>

    <meta-data
     android:name="com.google.android.maps.v2.API_KEY"
   android:value=" my key "/> 

    </application>
    </manifest>

这是xml:

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 tools:context=".MainActivity" >


 <fragment xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/map"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 class="com.google.android.gms.maps.MapFragment"/>

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_world" />

  </RelativeLayout>

我试图解决它,就像这个解决方案Google Maps Android API v2 throws GooglePlayServicesNotAvailableException, out of date, SupportMapFragment.getMap() returns null  ..但仍然没有工作

更新:

我的地图现在正在运行..这是已编辑的工作版

   public class MainActivity extends FragmentActivity {
 private GoogleMap myMap;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

          android.support.v4.app.FragmentManager myFragmentManager = getSupportFragmentManager();
          SupportMapFragment mySupportMapFragment 
           = (SupportMapFragment)myFragmentManager.findFragmentById(R.id.map);


             myMap = mySupportMapFragment.getMap();
             if(myMap!=null)
            myMap.setMyLocationEnabled(true);


        }

5 个答案:

答案 0 :(得分:17)

您正在通过FragmentTransaction创建动态片段。当您致电commit()时,该片段的尚未添加到屏幕上,因为FragmentTransaction仅计划发生 - 尚未发生。因此,尚未使用SupportMapFragment调用onCreateView(),因此没有GoogleMap

切换到静态片段(布局中的<fragment>标记),或延迟使用GoogleMap,直到处理完交易后。

答案 1 :(得分:6)

FragmentManager类中的

executePendingTransactions()旨在修复此延迟。 来自documantstion:在使用FragmentTransaction.commit()提交FragmentTransaction之后,它被安排在进程的主线程上异步执行。 如果要立即执行任何此类待处理操作,可以调用此函数(仅从主线程)来执行此操作。请注意,所有回调和其他相关行为都将在此调用中完成,因此请注意调用它的位置。

答案 2 :(得分:6)

我扩展了MapFragment类并添加了一个监听器。 关于getMap()的文档说:

  

...如果片段的视图尚未准备好,则为空。如果片段生命周期尚未通过onCreateView(LayoutInflater,ViewGroup,Bundle),则会发生这种情况....

然后我在onCreateView之后调用监听器。我添加了课程

public class MySupportMapFragment extends SupportMapFragment{

private MySupportMapFragmentListener listener;

public interface MySupportMapFragmentListener{
    public void onMapCreated(GoogleMap googleMap);
}

// value taken from source code
private static final String MAP_OPTIONS = "MapOptions";

public static MySupportMapFragment newInstance() {
        MySupportMapFragment f = new MySupportMapFragment();
        return f;
}

public static MySupportMapFragment newInstance(GoogleMapOptions options) {
        MySupportMapFragment f = new MySupportMapFragment();
        Bundle args = new Bundle();
        args.putParcelable(MAP_OPTIONS, options);
        f.setArguments(args);
        return f;
}

// other newInstance methods ...


/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onViewCreated(android.view.View, android.os.Bundle)
 */
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);
    // here, as doc say, the map can be initialized, or the service is not available
    if(listener!=null){
        listener.onMapCreated(getMap());
    }

}
/**
 * @return the listener
 */
public MySupportMapFragmentListener getListener() {
    return listener;
}
/**
 * @param listener the listener to set
 */
public void setListener(MySupportMapFragmentListener listener) {
    this.listener = listener;
}

}

在调用活动或片段之后......

    mapFragment = MySupportMapFragment.newInstance();
    mapFragment.setListener(new MySupportMapFragmentListener() {
        @Override
        public void onMapCreated(GoogleMap googleMap) {
            // TODO Auto-generated method stub          
            if(googleMap!=null){
                  // service is unaviable
            }               
        }

答案 3 :(得分:3)

移动代码段:

GoogleMap地图; map = fragment.getMap();

//此处地图不为空

如果(图!= NULL){

UiSettings mm = map.getUiSettings();
map.setMyLocationEnabled(true);

}

到onResume()方法,这将解决您的问题。

答案 4 :(得分:1)

另一种解决方法。在MapFragment中实现一个接口,以便在准备好创建GoogleMap时与活动进行通信。

    @Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);
    listener.onGoogleMapCreattion();


}

然后你只需要在活动中实现监听器:

    @Override
public void onGoogleMapCreation() {
    setUpMapIfNeeded();

}

    private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
         mMap = mMapFragment.getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
          // The Map is verified. It is now safe to manipulate the map.
            setUpMap();

        }
    }
  }