MapView google 映射 NullPointerException?

MapView google maps NullPointerException?

我正在尝试创建 如何使用 MapView 获取。我创建了一个 Fragment 和一个 XML 来使用它。问题是当我尝试打开 MapView 时抛出 NullPointerException 但我不明白为什么。

我该如何解决?

XML

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="160dp"
        android:layout_marginRight="10dp" />

</LinearLayout>

片段

public class FormComoChegarEmpresa extends Fragment{
    MapView mapView;
    private GoogleMap googleMap;
    private final String TAG = getClass().getSimpleName() + "->";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ((CustomDrawerLayout)getActivity()).getSupportActionBar().hide();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.como_chegar_empresa, container, false);
        mapView = (MapView)view.findViewById(R.id.mapView);


        return  view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setMapView();
    }

    private void setMapView() {
        try {
            MapsInitializer.initialize(getActivity().getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }

        googleMap = mapView.getMap();
        // latitude and longitude
        double latitude = 17.385044;
        double longitude = 78.486671;

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

        // Changing marker icon
        marker.icon(BitmapDescriptorFactory
                .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

        // adding marker
        googleMap.addMarker(marker);
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
        googleMap.animateCamera(CameraUpdateFactory
                .newCameraPosition(cameraPosition));

        // Perform any camera updates here
    }    

}

异常

java.lang.NullPointerException
            at br.com.package.myapp.frags.FormComoChegarEmpresa.setMapView(FormComoChegarEmpresa.java:80)
            at br.com.package.myapp.frags.FormComoChegarEmpresa.onActivityCreated(FormComoChegarEmpresa.java:56)
            at android.support.v4.app.Fragment.performActivityCreated(Fragment.java:1794)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:967)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
            at android.support.v4.app.FragmentManagerImpl.run(FragmentManager.java:454)
            at android.os.Handler.handleCallback(Handler.java:733)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:157)
            at android.app.ActivityThread.main(ActivityThread.java:5356)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
            at dalvik.system.NativeStart.main(Native Method)

我在第一次尝试使用 GoogleMap 和 MapView 时遇到了同样的问题。

问题是当您初始化地图时,加载需要很短的时间(它在后台加载)。当您从 MapView 获取实例时,GoogleMap 的值仍然为 null(未初始化)。

这里需要使用OnMapLoadedCallback。在 googleMap = mapView.getMap(); 之后将此回调的实例添加到 googleMap。回调主体有一个名为 onMapLoaded() 的函数,您可以在其中放置以下代码:

googleMap.addMarker(marker);
CameraPosition cameraPosition = new CameraPosition.Builder()
        .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory
        .newCameraPosition(cameraPosition));

'googleMap.<member>' 之类的东西。为了您的方便,我在下面添加了经过编辑的代码。

private void setMapView() {

    try {
        MapsInitializer.initialize(getActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    googleMap = mapView.getMap();

    googleMap.setOnMapLoadedCallback(new OnMapLoadedCallback()
    {
        @Override
        public void onMapLoaded()
        {
            // latitude and longitude
                double latitude = 17.385044;
                double longitude = 78.486671;

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

                // Changing marker icon
                marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));

                // adding marker
                googleMap.addMarker(marker);
                CameraPosition cameraPosition = new CameraPosition.Builder()
                        .target(new LatLng(17.385044, 78.486671)).zoom(12).build();
                googleMap.animateCamera(CameraUpdateFactory
                        .newCameraPosition(cameraPosition));

            // Perform any camera updates here

        }
    });
  }