SupportMapFragment make app crashed after getSuppo

2019-08-22 04:42发布

问题:

i have a problem to access SupportMapFragment, in this part of my code, its always returning NPE,

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

Here is my 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>

and my 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) {

            }
        }
    }
//...

and here my PlaceholderFragment

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

            return rootView;
        }

i think my manifest works fine, because everything is fine before i used googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map) but, for clearing my question, here my manifest file

<?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>

and here my log cat that explain to me NPE problem :

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

I have tried to find solution in SO, but no one can solve my problem, i have tried to :

  1. Used MapFragment by following this link but not solved my question.

  2. Following this solution and still give me some error.

  3. Following this not helped too.

  4. Following this question and not fixing my problem, so i make a new question here in SO.

  5. Following this link, link, and another link but no one can solve my problem.

  6. My Google play services work properly, so its not from Google Play Services.

Any advice? what's solution? many thanks, i really need this for my collage final project, any help would be appreciated it.

UPDATE

line 84 on Log Cat is :

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

回答1:

for your requirement you can see this link for GoogleMap v2 with ActionBar Git hub link

https://github.com/ddewaele/GoogleMapsV2WithActionBarSherlock

or u can use MapView in your activity

  • How to use MapView for GoogleMap v2

https://developers.google.com/maps/documentation/android/map#mapview



回答2:

Try like this:

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

Note: You need to extend FragmentActivity instead of ActionBarActivity.



回答3:

I suggest to you to do like following :

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>

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

You override onResume Method and you initilize the Map. This should work ;)



回答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:

Try This

In 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>

In Activity:-

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

Follow these Link 1 and Link 2 Hope it will help you to sort out with your problem Good Luck