【问题标题】:SupportMapFragment make app crashed after getSupportFragmentManager()SupportMapFragment 使应用程序在 getSupportFragmentManager() 后崩溃
【发布时间】:2014-06-03 16:42:26
【问题描述】:

我在访问 SupportMapFragment 时遇到问题, 在我的这部分代码中,它总是返回 NPE,

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

这是我的 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="yai.properti.tujuh.tujuh.tujuh.MainActivity$PlaceholderFragment" >

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

还有我的 MainActivity.java

//...
import android.app.Activity;
import android.app.Dialog;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.TextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
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.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends ActionBarActivity implements
        NavigationDrawerFragment.NavigationDrawerCallbacks {

    static final LatLng HAMBURG = new LatLng(53.558, 9.927);
    static final LatLng KIEL = new LatLng(53.551, 9.993);
    private GoogleMap googleMap;

    private NavigationDrawerFragment mNavigationDrawerFragment;

    private CharSequence mTitle;

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

        int status = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getBaseContext());

        if (status != ConnectionResult.SUCCESS) {

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
                    requestCode);
            dialog.show();
        } else { 
            setUpMapIfNeeded();
        }

        mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
                .findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();        

        mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));       
    }

    private void setUpMapIfNeeded() {
        if (googleMap == null) {
            // Part of my code that i get NPE
            // my code running well if i commenting this section
            //googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();               
            if (googleMap != null) {

            }
        }
    }
//...

这里是我的 PlaceholderFragment

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

            return rootView;
        }

我认为我的清单工作正常,因为在我使用之前一切都很好 googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map) 但是,为了解决我的问题,这里是我的清单文件

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

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="19" />

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

    <permission
        android:name="yai.properti.tujuh.tujuh.tujuh.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="yai.properti.tujuh.tujuh.tujuh.permission.MAPS_RECEIVE"/>
    <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" />

    <!-- Not Required in Map API v2 but highly recomended -->
    <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" >

        <uses-library
            android:name="com.google.android.maps" 
            android:required="true"
            />

        <!-- Initiating Activity -->
        <activity
            android:name="yai.properti.tujuh.tujuh.tujuh.InitiatingActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape"
            android:theme="@android:style/Theme.Black.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Welcome Activity -->
        <activity
            android:name="yai.properti.tujuh.tujuh.tujuh.WelcomeActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@android:style/Theme.Black.NoTitleBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.HOME" />
            </intent-filter>
        </activity>

        <!-- Main Activity -->
        <activity
            android:name="yai.properti.tujuh.tujuh.tujuh.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

        <!-- Login Activity -->
        <activity
            android:name="yai.properti.tujuh.tujuh.tujuh.LoginActivity"
            android:label="@string/title_activity_login"
            android:windowSoftInputMode="adjustResize|stateHidden" 
            android:screenOrientation="landscape"
            >
        </activity>

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

        <meta-data android:name="com.google.android.gms.version" 
           android:value="@integer/google_play_services_version" />
    </application>
</manifest>

这里是我的日志猫,它向我解释了 NPE 问题:

06-02 18:32:04.292: W/dalvikvm(32016): threadid=1: thread exiting with uncaught exception (group=0x41d0b2a0)
06-02 18:32:04.297: E/AndroidRuntime(32016): FATAL EXCEPTION: main
06-02 18:32:04.297: E/AndroidRuntime(32016): java.lang.RuntimeException: Unable to start activity ComponentInfo{yai.properti.tujuh.tujuh.tujuh/yai.properti.tujuh.tujuh.tujuh.MainActivity}: java.lang.NullPointerException
06-02 18:32:04.297: E/AndroidRuntime(32016):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at android.app.ActivityThread.access$700(ActivityThread.java:140)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at android.os.Handler.dispatchMessage(Handler.java:99)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at android.os.Looper.loop(Looper.java:137)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at android.app.ActivityThread.main(ActivityThread.java:4921)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at java.lang.reflect.Method.invokeNative(Native Method)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at java.lang.reflect.Method.invoke(Method.java:511)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at dalvik.system.NativeStart.main(Native Method)
06-02 18:32:04.297: E/AndroidRuntime(32016): Caused by: java.lang.NullPointerException
06-02 18:32:04.297: E/AndroidRuntime(32016):    at yai.properti.tujuh.tujuh.tujuh.MainActivity.setUpMapIfNeeded(MainActivity.java:84)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at yai.properti.tujuh.tujuh.tujuh.MainActivity.onCreate(MainActivity.java:68)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at android.app.Activity.performCreate(Activity.java:5188)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
06-02 18:32:04.297: E/AndroidRuntime(32016):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
06-02 18:32:04.297: E/AndroidRuntime(32016):    ... 11 more

我试图在 SO 中找到解决方案,但没有人能解决我的问题, 我已经尝试过:

  1. 按照link 使用 MapFragment,但没有解决我的问题。

  2. 按照这个solution 仍然给我一些错误。

  3. 关注this 也无济于事。

  4. 关注this 问题并没有解决我的问题,所以我在这里提出了一个新问题。

  5. 关注这个linklink和另一个link,但没有人能解决我的问题。

  6. 我的 Google Play 服务工作正常,所以它不是来自 Google Play 服务。

有什么建议吗?有什么解决办法?非常感谢,我的拼贴最终项目真的需要这个,任何帮助将不胜感激。

更新

Log Cat 上的第 84 行是:

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

【问题讨论】:

  • 一旦在第 84 行调试和检查,有些东西就变成了空值。
  • @shylendra 感谢您的回复,这是我的googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
  • 你可以用ActionBarActivity代替FragmentActivity试试看
  • @john : 你在哪里写了那行代码??
  • 是的,kaushik 说的对,你需要扩展 FragmentActivity

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


【解决方案1】:

【讨论】:

    【解决方案2】:

    试试这样:

    if (googleMap == null) {
                android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
                googleMap = ((SupportMapFragment) fragmentManager.findFragmentById(R.id.map)).getMap();
                Log.i("Google map", "Successfully Googlemap is opened");
    }
    

    注意:您需要扩展 FragmentActivity 而不是 ActionBarActivity。

    【讨论】:

      【解决方案3】:

      我建议你这样做:

      XML:

      <FrameLayout 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" >
      
             <fragment
              android:id="@+id/map"
              android:name="com.google.android.gms.maps.MapFragment"
              android:layout_width="match_parent"
              android:layout_height="match_parent"/>
      
      </FrameLayout>
      

      您的 MainActivity:

      private GoogleMap googleMap;
          private MapView mMapView;
      
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
      
              setContentView(R.layout.activity_show_post);
      
              final View controlsView = findViewById(R.id.fullscreen_content_controls);
              final View contentView = findViewById(R.id.map);
      
              initilizeMap(); 
          }
      
          private void initilizeMap() {
              if (googleMap == null) {
                  googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                          R.id.map)).getMap();
      
                  // check if map is created successfully or not
                  if (googleMap == null) {
                      Toast.makeText(getApplicationContext(),
                              "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                              .show();
                  }
              }
          }
      
          @Override
          protected void onResume() {
              super.onResume();
              initilizeMap();
          }
      

      您覆盖 onResume 方法并初始化 Map。这应该工作;)

      【讨论】:

      • 你调用方法initializeMap两次有什么原因吗?
      【解决方案4】:
      private GoogleMap map;
      private SupportMapFragment mapFragment;
      
      // in onCreate() or in onStart() do some thing like this
      
      fragmentManager = getSupportFragmentManager();
          mapFragment = (SupportMapFragment) fragmentManager
                  .findFragmentById(R.id.maps_parks);
          map = mapFragment.getMap();
      

      【讨论】:

        【解决方案5】:

        试试这个

        在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"
                class="com.google.android.gms.maps.MapFragment"
                 />
        
            </LinearLayout>
        

        活动中:-

            public class ActivityMain extends Activity {
                // Google Map
                public GoogleMap googleMap;
        
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
        
                try {
                    Log.e("loading map. . . .", "loading map. . . ");
                    // Loading map
                    initilizeMap();
        
                } catch (Exception e) {
                    Log.e("catch. . .", "catch. . .");
                    e.printStackTrace();
                }
                /*
                 * MapFunctionality mf = new MapFunctionality(); mf.currentLoc();
                 * mf.addMarker();
                 */
            }
        
            /**
             * function to load map. If map is not created it will create it for you
             * */
            private void initilizeMap() {
                // MapFunctionality mf = new MapFunctionality();
                Log.e("initializing map. . . ", "initializing map. . ");
                if (googleMap == null) {
                    googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                            R.id.map)).getMap();
        
                    // check if map is created successfully or not
                    if (googleMap == null) {
                        Toast.makeText(getApplicationContext(),
                                "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                                .show();
                    }
                    // mf.currentLoc();
                    // mf.addMarker();
                }
            }
        
            @Override
            public boolean onCreateOptionsMenu(Menu menu) {
                // Inflate the menu; this adds items to the action bar if it is present.
                getMenuInflater().inflate(R.menu.activity_main, menu);
                return true;
            }
        
            @Override
            protected void onResume() {
                super.onResume();
                initilizeMap();
            }
        }
        

        关注Link 1Link 2 希望它能帮助你解决你的问题 祝你好运

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-03-09
          相关资源
          最近更新 更多