【问题标题】:getMap() in onCreate(), created from layout gives nullpointerexception从布局创建的 onCreate() 中的 getMap() 给出 nullpointerexception
【发布时间】:2026-02-19 06:50:02
【问题描述】:

这是我的代码:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

在 onCreate() 方法内部:(我在 onCreate() 只有这个,除了包创建和变量分配,使用那个包。)

FragmentManager myFM = getSupportFragmentManager();
SupportMapFragment myMAPF =(SupportMapFragment)myFM.
      findFragmentById(R.id.mapfragment);
map=myMAPF.getMap();//Exception at this line

布局:

<fragment
    android:id="@+id/mapfragment"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" />

清单:

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

不得不提一下,我在生成api密钥的时候,复制了debug.keystore文件,存放在更方便的位置,然后生成了。我对原始位置的原始文件再次执行此操作,但返回了相同的 SH1,因此我没有生成另一个 API 密钥。已在 API 访问页面中激活中断器。

我之前看到过一些回答问同样的问题,我已经尝试了很多他们的解决方案......没有运气。

我正在使用 Eclipse 的 Android 版本 4.0 的设备上通过 USB 运行该应用程序。

谁能帮我找出错误在哪里?谢谢。

编辑

抱歉,忘记了 StackTrace

10-23 13:54:53.230: E/AndroidRuntime(6786): java.lang.RuntimeException: Unable to start activity ComponentInfo{mypackage/mypackage.MapActivity}: java.lang.NullPointerException
10-23 13:54:53.230: E/AndroidRuntime(6786):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at android.os.Handler.dispatchMessage(Handler.java:99)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at android.os.Looper.loop(Looper.java:137)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at android.app.ActivityThread.main(ActivityThread.java:4424)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at java.lang.reflect.Method.invokeNative(Native Method)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at java.lang.reflect.Method.invoke(Method.java:511)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at dalvik.system.NativeStart.main(Native Method)
10-23 13:54:53.230: E/AndroidRuntime(6786): Caused by: java.lang.NullPointerException
10-23 13:54:53.230: E/AndroidRuntime(6786):     at mypackage.MapActivity.onCreate(MapActivity.java:73)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at android.app.Activity.performCreate(Activity.java:4470)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
10-23 13:54:53.230: E/AndroidRuntime(6786):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)

我刚刚注意到一件奇怪的事情,在堆栈跟踪的第一行中,我的应用程序的完整包的两倍...为什么会发生这种情况?

【问题讨论】:

  • 请发布日志,包括完整的异常堆栈跟踪。
  • 贴上完整的onCreate函数代码
  • 可能是因为地图对象还没有准备好。查看演示 API,它们使用回调来判断它何时准备就绪。
  • 您的代码中的map 是什么?你不能发布完整的代码吗?
  • 不...我很抱歉,但我不能。 map 是一个 GoogleMap 实例 GoogleMap 地图;一个全局变量。

标签: android nullpointerexception supportmapfragment


【解决方案1】:

您的地图尚不可用...您可以使用类似以下方法来确定 Play Services 在使用之前是否可用(我会在 onActivityCreated 中调用它,而不是在 onCreate 中调用):

protected boolean isPlayServicesAvailable() {
    int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);

    if (status == ConnectionResult.SUCCESS) {
        return (true);
    } else if (GooglePlayServicesUtil.isUserRecoverableError(status)) {
        // deal with error
    } else {
            // maps is not available
    }

    return (false);
}

此外,您的 Fragment 需要实现 Play 服务所需的回调(接口 GooglePlayServicesClient.ConnectionCallbacks 和 GooglePlayServicesClient.OnConnectionFailedListener :

    /*
     * Called by Location Services when the request to connect the
     * client finishes successfully. At this point, you can
     * request the current location or start periodic updates
     */
    @Override
    public void onConnected(Bundle dataBundle) {
        // Display the connection status
        Toast.makeText(context, "Connected to location services", Toast.LENGTH_SHORT).show();

    }

    /*
     * Called by Location Services if the connection to the
     * location client drops because of an error.
     */
    @Override
    public void onDisconnected() {
        // Display the connection status
        Toast.makeText(context, "Disconnected from location services. Please re-connect.",
                Toast.LENGTH_SHORT).show();
    }

    /*
     * Called by Location Services if the attempt to
     * Location Services fails.
     */
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        /*
         * Google Play services can resolve some errors it detects.
         * If the error has a resolution, try sending an Intent to
         * start a Google Play services activity that can resolve
         * error.
         */
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(
                        SomeActivity,
                        CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Toast.makeText(context, "Connection error", Toast.LENGTH_SHORT).show();
        }
    }
}

编辑: 这就是我在包含地图片段的活动中使用它的方式:

if (isPlayServicesAvailable()) {
    setContentView(R.layout.activity_with_map_fragment);
}

在片段中:

if (getMap() != null) {
    GoogleMap map = getMap();
    // do things with the map
}

这应该会让你继续前进 ;-)

【讨论】:

  • 我要试试这个。
  • 嗯...我认为没关系,因为 isPlayServicesAvailable() 返回 false,因为我还没有安装最新的 google play 服务。我今天回来做,现在它是最新的......我仍然得到一个空指针异常......
  • 您的 Fragment 是否扩展了 MapFragment (developer.android.com/reference/com/google/android/gms/maps/…)?
  • 原来是缺少权限。再次感谢!
  • 很高兴您找到了问题的根源;)