【问题标题】:NullPointerException using GoogleMaps in AndroidNullPointerException 在 Android 中使用 GoogleMaps
【发布时间】:2014-05-20 16:08:36
【问题描述】:

我的代码在我的代码的这一行抛出了NullPointerException

map=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap()

我可以看到它在 LogCat 中引发了异常。我已经尝试过多次解决这个问题,并且我已经阅读了这个论坛上所有类似的问题。我尝试了一些解决方案,但徒劳无功。当我注释掉该行时,我会显示 Google 地图,但是当我尝试在我的代码中获取片段时,我仍然会遇到同样的异常。

这是我的代码:

package cs.exmpl;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;

public class MainActivity extends ActionBarActivity {
    private GoogleMap map;
    private final LatLng loc=new LatLng(566544, 556554);

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

            map=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

        //SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
       // map = mapFrag.getMap();



            map.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
        CameraUpdate up=CameraUpdateFactory.newLatLngZoom(loc, 14);
        map.animateCamera(up);






        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container,
                    false);
            return rootView;
        }
    }

}

这是我的 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="cs.exmpl.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

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

</RelativeLayout>

【问题讨论】:

  • map=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); 移动到 onStart。视图可能尚未完全绘制,因此它可能返回 null。
  • 你能说得更清楚些吗?我不明白你的意思谢谢你
  • setContentView 表示您想要扩充包含地图视图的布局,但它不会立即执行此操作。一旦您的视图完成绘制(因此您的片段已准备好被获取),就会调用 onStart。
  • @user3448582 什么是 min sdk 是否低于 11,因为您扩展了 ActionBarActivity 在这种情况下您将需要使用 SupportMapFragment
  • 你能给出能解决我问题的指令吗

标签: android google-maps maps


【解决方案1】:

getMap() 可以返回 null

引用文档

GoogleMap 只能在底层使用 getMap() 获取 地图系统已加载并且片段中的底层视图存在。 该类自动初始化地图系统和视图; 但是你不能保证它什么时候准备好,因为这 取决于 Google Play 服务 APK 的可用性。如果一个 GoogleMap 不可用,getMap() 将返回 null。

在初始化GoogleMap对象之前检查google play服务的可用性。

检查主题检查 Google Play 服务

http://developer.android.com/training/location/retrieve-current.html

编辑:

tools:context="cs.exmpl.MainActivity$PlaceholderFragment"

看起来MapFragment 也处于片段布局中,而您在 Activity 中对其进行了初始化。使用MapView 关注

Android - android.view.InflateException: Binary XML file line #8: Error inflating class fragment

或扩展MapFragment 而不是Fragment

编辑 3:

例子:

activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="cs.exmpl.MainActivity"
    tools:ignore="MergeRootFrame" />

fragment_main.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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="cs.exmpl.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/header"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

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


</RelativeLayout>

MainActivity.java

public class MainActivity extends ActionBarActivity {

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

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        MapView mapView;
        GoogleMap map;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main, container, false);
        // Gets the MapView from the XML layout and creates it

        MapsInitializer.initialize(getActivity());


        switch (GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()) )
        {
        case ConnectionResult.SUCCESS:
          Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT).show();
          mapView = (MapView) v.findViewById(R.id.map);
          mapView.onCreate(savedInstanceState);
          // Gets to GoogleMap from the MapView and does initialization stuff
          if(mapView!=null)
          {
          map = mapView.getMap();
          map.getUiSettings().setMyLocationButtonEnabled(false);
          map.setMyLocationEnabled(true);
          CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
          map.animateCamera(cameraUpdate);
          }
          break;
        case ConnectionResult.SERVICE_MISSING: 
          Toast.makeText(getActivity(), "SERVICE MISSING", Toast.LENGTH_SHORT).show();
          break;
        case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED: 
          Toast.makeText(getActivity(), "UPDATE REQUIRED", Toast.LENGTH_SHORT).show();
          break;
        default: Toast.makeText(getActivity(), GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity()), Toast.LENGTH_SHORT).show();
        }




        // Updates the location and zoom of the MapView

        return v;
        }

        @Override
        public void onResume() {
        mapView.onResume();
        super.onResume();
        }
        @Override
        public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        }
        @Override
        public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
        }
        }

}

清单

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

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

     <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
     <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
     <!-- The following two permissions are not required to use
     Google Maps Android API v2, but are recommended. -->
     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
     <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="cs.exmpl.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="YOUR API KEY FROM GOOGLE API CONSOLE"/>
        <meta-data android:name="com.google.android.gms.version"
          android:value="@integer/google_play_services_version" />
    </application>

</manifest>

卡在设备上

【讨论】:

  • @user3448582 为什么我想看那个教程。请改用文档。
  • @user3448582 发布了一个完整的示例。由您自行修改以进行相应的修改。注意要在模拟器上进行测试,您需要 google 平台 4.4.2 及更高版本。
  • 好的,Raghunandan 我会试试的。告诉我 activity_main.xml 它仍然没有变化吗?
  • @user3448582 发布了所有内容。所有你需要参考谷歌播放服务。从 google api 控制台生成地图 api 密钥。将其复制到清单中。其余的只是从这里复制粘贴。我认为你也不需要帮助。如果您需要帮助,也可以谷歌搜索或在 stackoverflow 上搜索,我自己已经回答了一些。
  • @user3448582 我发布了这两个帖子,请再次查看帖子。您甚至完整阅读了帖子吗?我发布了整个项目代码,因为我知道您最终会再次询问。除了从这里复制粘贴,别无他法
【解决方案2】:

这是因为findFragmentById在activity_main布局中搜索,而Map位于fragment的布局fragment_main中。

在片段的onCreateView() 方法中移动那段代码:

//...
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
map=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
//...

请注意,现在您可以通过rootView view 访问它:

否则你会再次收到NullPointerException

编辑

所以改变你的onCreateView()如下

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);
        map=((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
        return rootView;
    }

【讨论】:

  • 你能告诉我我是android编程新手该怎么做吗?谢谢
  • 查看编辑...您只需执行此操作并将其从 onCreate() 中删除
  • 他得到NPE 的原因是zgc7009 所说的。 MapFragment 直到 onCreate() 之后才会膨胀,因为 onCreateView()onCreate() 之后被调用。
  • 你的意思是我删除了 oncreateView 里面的内容吗?
  • 我知道您想快速获得声誉,但不要以牺牲清晰度和实际提供高质量答案为代价。这里重要的是解释他为什么要获得 NPE。例如,他甚至没有在代码中的任何地方使用findViewById(),他确实尝试正确地获取Fragment 的引用,但不是在正确的时间。
猜你喜欢
  • 1970-01-01
  • 2013-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-03
  • 2016-11-11
相关资源
最近更新 更多