NullPointerException using SupportMapFragment

杀马特。学长 韩版系。学妹 提交于 2019-12-11 01:34:49

问题


I'm trying to resolve this issue for some days. I'm vorking with GoogleMaps and SupportMapFragment. When I launch my app, log show this error and my app crash.

Here is my log cat:

12-05 11:16:03.437    6931-6931/it.home.dressgallery E/dalvikvm﹕ Could not find class 'android.app.Notification$Builder', referenced from method com.google.android.gms.common.GooglePlayServicesUtil.showErrorNotification
12-05 11:16:08.406    6931-6931/it.home.dressgallery E/dalvikvm﹕ Could not find class 'android.app.Notification$Builder', referenced from method com.google.android.gms.common.l.c
12-05 11:16:08.601    6931-6931/it.home.dressgallery E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.NullPointerException
            at com.google.maps.api.android.lib6.c.aa.b(Unknown Source)
            at com.google.android.gms.maps.internal.x.onTransact(SourceFile:115)
            at android.os.Binder.transact(Binder.java:279)
            at com.google.android.gms.maps.internal.IMapFragmentDelegate$a$a.onResume(Unknown Source)
            at com.google.android.gms.maps.SupportMapFragment$a.onResume(Unknown Source)
            at com.google.android.gms.dynamic.a$7.b(Unknown Source)
            at com.google.android.gms.dynamic.a.a(Unknown Source)
            at com.google.android.gms.dynamic.a.onResume(Unknown Source)
            at com.google.android.gms.maps.SupportMapFragment.onResume(Unknown Source)
            at android.support.v4.app.Fragment.performResume(Fragment.java:1547)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:978)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1121)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
            at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:482)
            at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
            at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
            at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
            at android.view.View.measure(View.java:8366)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
            at android.view.View.measure(View.java:8366)
            at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
            at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
            at android.view.View.measure(View.java:8366)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
            at android.view.View.measure(View.java:8366)
            at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
            at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
            at android.view.View.measure(View.java:8366)
            at android.view.ViewRoot.performTraversals(ViewRoot.java:844)
            at android.view.ViewRoot.handleMessage(ViewRoot.java:1865)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:130)
            at android.app.ActivityThread.main(ActivityThread.java:3687)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
            at dalvik.system.NativeStart.main(Native Method)

Here is my AndroidManifest.xml:

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

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

    <permission
        android:name="it.home.dressgallery.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />
    <uses-permission android:name="it.home.dressgallery.permission.MAPS_RECEIVE" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <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"/>

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppBaseTheme"
        android:hardwareAccelerated="true" >


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

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

        <activity
            android:name="it.home.dressgallery.MeinActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>


    </application>

</manifest>

This is maps_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

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

</FrameLayout>

This is MapsFragment.java class:

package it.home.dressgallery;

import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

/**
 * Created by tank on 04/12/14.
 */
public class MapsFragment extends SupportMapFragment {

    private GoogleMap googleMap;

    // latitude and longitude
    double latitude = 17.385044;
    double longitude = 78.486671;

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.maps_layout, container, false);

        initializeMap();
        myAddMarker(latitude, longitude, BitmapDescriptorFactory.HUE_ORANGE);
        googleMap.setMyLocationEnabled(true); // false to disable
        googleMap.getUiSettings().setZoomControlsEnabled(false); // true to enable
        googleMap.getUiSettings().setCompassEnabled(true);
        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
        //googleMap.getUiSettings().setRotateGesturesEnabled(true);

        Marker hamburg = googleMap.addMarker(new MarkerOptions().position(HAMBURG)
                .title("Hamburg"));
        Marker kiel = googleMap.addMarker(new MarkerOptions()
                .position(KIEL)
                .title("Kiel")
                .snippet("Kiel is cool")
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.ic_launcher)));

        // Move the camera instantly to hamburg with a zoom of 15.
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));

        // Zoom in, animating the camera.
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);

        return view;
    }

    /**
     * function to load map. If map is not created it will create it for you
     * */
    private void initializeMap() {
        if (googleMap == null) {
            googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

            // check if map is created successfully or not
            if (googleMap == null) {
                Toast.makeText(getActivity().getApplicationContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * Function to add a marker on the map
     * @param latitude
     * @param longitude
     * @param color
     */
    public void myAddMarker(double latitude, double longitude, float color){

        // create and add marker
        Marker marker = googleMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude))
                .title("Hello Maps ").icon(BitmapDescriptorFactory.defaultMarker(color)));

    }

    /**
     * Apart from maps native marker icons, you can use own image to show as a marker. You can load the icon from any kind of supported sources.
     * fromAsset(String assetName) – Loading from assets folder
     * fromBitmap (Bitmap image) – Loading bitmap image
     * fromFile (String path) – Loading from file
     * fromResource (int resourceId) – Loading from drawable resource
     */
    public void myAddMarkerCustom(double latitude, double longitude, int my_marker_icon){

        // create marker
        MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");

        // Changing marker icon
        marker.icon(BitmapDescriptorFactory.fromResource(my_marker_icon));

        // adding marker
        googleMap.addMarker(marker);
    }

    public void moveToPosition(long latitude, long longitude, float zoom){
        CameraPosition cameraPosition = new CameraPosition.Builder().target(
                new LatLng(latitude, longitude)).zoom(zoom).build();

        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }

    /**
     * googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
     * googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
     * googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
     * googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
     * googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
     */
    public void myChangeMap(int type){
        googleMap.setMapType(type);
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            //selectItem(position);
            //TODO...add something to do
        }
    }

}

I hope someone can help me, because I'm freaking out. Thanks!!!


回答1:


Where is super.onCreateView of your Fragment

so the solution is to add the following line:

super.onCreateView(inflater, container, savedInstanceState);

your onCreateView() method is useless without it.

Solution:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);

    View view = inflater.inflate(R.layout.maps_layout, container, false);

    initializeMap();
    myAddMarker(latitude, longitude, BitmapDescriptorFactory.HUE_ORANGE);
    googleMap.setMyLocationEnabled(true); // false to disable
    googleMap.getUiSettings().setZoomControlsEnabled(false); // true to enable
    googleMap.getUiSettings().setCompassEnabled(true);
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
    //googleMap.getUiSettings().setRotateGesturesEnabled(true);

    Marker hamburg = googleMap.addMarker(new MarkerOptions().position(HAMBURG)
            .title("Hamburg"));
    Marker kiel = googleMap.addMarker(new MarkerOptions()
            .position(KIEL)
            .title("Kiel")
            .snippet("Kiel is cool")
            .icon(BitmapDescriptorFactory
                    .fromResource(R.drawable.ic_launcher)));

    // Move the camera instantly to hamburg with a zoom of 15.
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(HAMBURG, 15));

    // Zoom in, animating the camera.
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);

    return view;
}


来源:https://stackoverflow.com/questions/27314693/nullpointerexception-using-supportmapfragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!