向谷歌地图添加标记时出现空指针异常

时间:2014-12-31 11:25:15

标签: android google-maps google-maps-markers

我正在尝试在我的Android应用中为谷歌地图添加一个标记。但是我在运行app时遇到了一个空点异常。我没看到我的代码可能出错的地方。

这是我用过的代码

GoogleMap googleMap = null;

            MapFragment fm = (MapFragment) (activity.getFragmentManager())
                    .findFragmentById(R.id.map);

            googleMap = fm.getMap();
            googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(7.421226f,80.401264f))
            .title("Hello world"));

logcat的

12-31 16:51:54.667: E/AndroidRuntime(10191): FATAL EXCEPTION: main
12-31 16:51:54.667: E/AndroidRuntime(10191): java.lang.NullPointerException
12-31 16:51:54.667: E/AndroidRuntime(10191):    at com.fortuna.cinemalk.adapter.ViewPageAdapter.instantiateItem(ViewPageAdapter.java:201)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:829)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at android.support.v4.view.ViewPager.populate(ViewPager.java:979)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at android.support.v4.view.ViewPager.populate(ViewPager.java:911)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at android.support.v4.view.ViewPager.setAdapter(ViewPager.java:440)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at com.fortuna.cinemalk.TheaterDetailFragment$BackGround.onPostExecute(TheaterDetailFragment.java:148)
12-31 16:51:54.667: E/AndroidRuntime(10191):    at com.fortuna.cinemalk.TheaterDetailFragment$BackGround.onPostExecute(TheaterDetailFragment.java:1)

6 个答案:

答案 0 :(得分:1)

1)片段可能为空。

除非在布局中定义地图片段,否则您无法在onCreate中找到它。 (如果是这种情况,请告诉我,我会更新答案。)

2)片段尚未加载地图。

这是更可能的情况。您可以拥有MapFragment的实例,但它不必具有GoogleMap的实例。最新的Google Play服务SDK(v6.5.87)为您提供了方法MapFragment.getMapAsync(OnMapReadyCallback)。一旦GoogleMap实例可用,回调就会立即运行。只有这样你才能使用它。

答案 1 :(得分:0)

编辑:正如其他答案所提到的那样,getMap()现在实际上是折旧

因此,不再推荐使用以下方法,但仍可以使用。


首先确保您已输入AndroidManifest.xml

的Maps API密钥
<meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="api-key-here" />

然后确保在布局中正确定义地图(参见下面的示例)

<?xml version="1.0" encoding="utf-8"?>

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

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

 </RelativeLayout>   

完成后,您可以按如下方式访问地图

 android.support.v4.app.FragmentManager mFragmentManager = getSupportFragmentManager();
 final SupportMapFragment mMapFragment = (SupportMapFragment) mFragmentManager.findFragmentById(R.id.mapView);
 googleMap = mMapFragment.getMap();

答案 2 :(得分:0)

你检查过地图实际加载了吗?我猜测空指针异常实际上来自地图,而不是在其上放置标记。

本教程是开始使用谷歌地图的一个很好的指南(包括处理这样的例外): http://www.vogella.com/tutorials/AndroidGoogleMaps/article.html

答案 3 :(得分:0)

显然,问题必须与地图本身有关,而不是标记。

首先,请检查您使用哪个版本的Google Play服务作为库。 如果您在6.5 version之前有一些内容(2014年12月发布),请查看以下代码(Google Play服务示例中的信用额),以确保您没有空地图对象。

/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.mapdemo;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

/**
 * 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 BasicMapDemoActivity 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"));
    }
}



我强烈建议的另一个解决方案是获取最新的Google Play服务库(请查看here)。然后,您必须根据this guide从谷歌使用getMapAsync()(而不是getMap())和回调中更改代码,只要地图可以使用,您就可以执行任何操作,没有任何麻烦。

答案 4 :(得分:0)

不推荐使用getMap ,请改用getMapAsync。您的活动需要实现OnMapReadyCallback接口,因此您可以在onMapReady方法中添加标记。

来自文档:

  

的GetMap()   不推荐使用此方法。请改用getMapAsync(OnMapReadyCallback)。回调方法为您提供了一个保证非空并准备好使用的GoogleMap实例。

答案 5 :(得分:0)

  1. 首先使用此方法查看Google地图为空或无空 - &gt;如果(GMAP!= NULL)
  2. 是否必须直接从url.its下载标记图标表单网址(或)将标记图像添加到标记信息窗口,以获取网络主线程异常。
  3. 网络主线程异常会导致标记图像为null,因此您可能会在Google地图
  4. 中获得空指针异常

    解决方案:

    在onCreate方法中添加以下行

    function dblLinear(n) {
      if(n === 0) {
        return 1;
      } else if(n % 2 === 0) {
        return dblLinear(n-1) * 3 + 1;
      } else {
        return dblLinear(n-1) * 2 + 1;
      }
    }