【问题标题】:in google maps V2 ... fragment.getMap() returns null在谷歌地图 V2 ... fragment.getMap() 返回 null
【发布时间】:2013-02-01 07:49:45
【问题描述】:

我无法获取地图!我能得到的都是空的。

这里是代码。

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


        }

【问题讨论】:

  • 你的解决方案更新让它为我工作。 +1

标签: java android google-maps


【解决方案1】:

您正在通过FragmentTransaction 创建一个动态片段。当您调用commit() 时,该片段尚未被添加到屏幕上,因为FragmentTransaction 只是被安排发生——它还没有发生。因此,SupportMapFragment 还没有被onCreateView() 调用,所以没有GoogleMap

要么切换到静态片段(布局中的&lt;fragment&gt; 标记),要么延迟使用GoogleMap,直到事务处理完毕。

【讨论】:

  • 对不起:$ 但是我怎么能延迟使用 GoogleMap 我试图在 onResume() 中调用它但没有工作..不确定你的意思
  • @proG:在事务上调用commit() 后,在一些View 上调用post()(或者如果你有Handler)。当您计划的Runnable 被调用时,GoogleMap 应该已经存在。或者,再次切换到静态片段。
  • 我通过xml布局使用静态片段,但是有些手机还是有这个问题。一位测试员的 GS2 工作,而另一位测试员的 GS2 不工作。这是否与设备上无法使用 Google Play 服务有关?
  • @JMRboosties:不,只要您早在尝试使用 Maps V2 实际做任何事情之前就应该发现这是问题所在。
【解决方案2】:
FragmentManager 类中的

executePendingTransactions() 旨在解决此延迟问题。 来自文档:在使用 FragmentTransaction.commit() 提交 FragmentTransaction 后,它被安排在进程的主线程上异步执行。 如果您想立即执行任何此类挂起操作,您可以调用此函数(仅从主线程)来执行此操作。请注意,所有回调和其他相关行为都将在此调用中完成,因此请注意从何处调用它。

【讨论】:

  • 在调用 fragMan.executePendingTransactions() 之后我也无法获取 Map,同样的 NullPointerException 发生
  • 我也试过executePendingTransactions,调用后还是空。
【解决方案3】:

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

... 如果片段的视图尚未准备好,则为 Null。如果片段生命周期尚未通过 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
            }               
        }

【讨论】:

  • 很好的解决方案,目前看来是最优的了
  • 不能直接用onViewCreated代替吗?
【解决方案4】:

移动代码sn-p:

谷歌地图; map = fragment.getMap();

//这里的map不为空

如果(地图!=空){

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

}

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

【讨论】:

    【解决方案5】:

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

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

    那么你只需要在activtiy中实现监听即可:

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

    【讨论】:

    • 最佳答案。处理创建过程的异步性质是走向 IMO 的正确方法。其他任何事情,而您现在只是猜测是访问该对象的正确时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    相关资源
    最近更新 更多