java - 使用 GoogleMap V2 时 Android 应用程序不断崩溃

标签 java android google-maps google-maps-api-2

我在使用 GoogleMap 时遇到了一个恼人的问题。我已经测试过了, map 显示得很好。但现在我想将“我的位置”设置为“启用”,以便 map 自动从手机所在的位置开始。现在每次我运行该应用程序时它都会崩溃。我注意到,当我使用 GoogleMap 语法时,应用程序崩溃了。 我试图找出这个问题并在网上查了一下没有结果。

这是我的 Maps.java 文件:

package test.test;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;

import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

public class Maps extends FragmentActivity implements LocationListener{

    GoogleMap googlemap;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maps);
        SupportMapFragment mf = (SupportMapFragment)     getSupportFragmentManager().findFragmentById(R.id.map);
        googlemap = mf.getMap();

        googlemap.setMyLocationEnabled(true);
        googlemap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

    }

Maps.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

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

</LinearLayout>

最后是我的 androidmanifest:

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

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="16" />

        <permission
            android:name="test.test.permission.MAPS_RECEIVE"
            android:protectionLevel="signature" />

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

        <uses-feature
            android:glEsVersion="0x00020000"
            android:required="true" />

        <application

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

这是错误日志:

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{test.test/test.test.Maps}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5039)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at test.test.Maps.onCreate(Maps.java:23)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
... 11 more

最佳答案

该 fragment 尚未准备好,或者设备上的 Google Play 服务出现问题。

来自the docs (强调):

Returns
the GoogleMap. Null if the view of the fragment is not yet ready. This can happen if the fragment lifecyle have not gone through onCreateView(LayoutInflater, ViewGroup, Bundle) yet. This can also happen if Google Play services is not available. If Google Play services becomes available afterwards and the fragment have gone through onCreateView(LayoutInflater, ViewGroup, Bundle), calling this method again will initialize and return the GoogleMap.

“ map ”演示应用程序展示了一种处理此问题的模式,它会在创建和恢复时尝试根据需要设置 map :

/**
 * This shows how to create a simple activity with a map and a marker on the map.
 * <p>
 * Notice how we deal with the possibility that the Google Play services APK is not
 * installed/enabled/updated on a user's device.
 */
public class BasicMapActivity extends FragmentActivity {
    /**
     * Note that this may be null if the Google Play services APK is not available.
     */
    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.basic_demo);
        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     * <p>
     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not have been
     * completely destroyed during this process (it is likely that it would only be stopped or
     * paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
     * {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }
}

关于java - 使用 GoogleMap V2 时 Android 应用程序不断崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15098243/

相关文章:

javascript - Google Maps JS API 不会在移动设备上加载标记(在桌面上完美运行)

java - 如何在 json 数组中将 boolean 值写为字符串?

java - Freemarker 日期分配看似有效日期失败

java - 如何为字段创建具有枚举类型的对象

android - RemoteEmbeddedPlayer 不支持嵌入配置?

google-maps - Google map 未使用 Ionic 2 原生 google-maps 插件显示

java - 这个 while 循环似乎没有循环 - 循环中只有数学

android - 如何以编程方式将 tableRow 添加到 Xamarin 中的 TableLayout

android - 如何在 Android 工具栏中的 WhatsApp 等操作模式菜单中始终显示 5 个项目

android - picasso 图像未在自定义信息窗口中加载为什么?