SupportMapFragment使应用程序在getSupportFragmentManager()之后崩溃

时间:2014-06-02 11:37:52

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

我有访问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服务。

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

    更新

    Log Cat上的第84行是:

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

5 个答案:

答案 0 :(得分:1)

试试这样:

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。

答案 1 :(得分:1)

答案 2 :(得分:0)

我建议你这样做:

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>

您的主要活动:

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。这应该工作;)

答案 3 :(得分:0)

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();

答案 4 :(得分:0)

试试这个

在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 希望它能帮助您解决问题 祝你好运