在片段空指针的Andr​​oid地图 [英] Android map in fragment nullpointer

查看:94
本文介绍了在片段空指针的Andr​​oid地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目我试着去实现该解决方案用于管理动态添加片段的图谱。

In my project im trying to implementthis solution for managing a map in a dynamic added fragment.

public class MapFragment extends Fragment {
    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    static final LatLng KIEL = new LatLng(53.551, 9.993);
    private GoogleMap map;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v =inflater.inflate(R.layout.fragment_map, container, false);

        map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();

        Marker kiel = map.addMarker(new MarkerOptions()
                .position(KIEL)
                .title("Kiel")
                .snippet("Kiel is cool")
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.ic_arrow)));

        // Move the camera instantly to hamburg with a zoom of 15.
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(KIEL, 15));
        // Zoom in, animating the camera.
        map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
        return v;
    }
}

我的看法:

<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:background="@color/ColorBackground"
    tools:context="com.example.sven.questy.GameFragments.MapFragment">

    <fragment

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

</RelativeLayout>

当我运行的应用程序,我得到一个空指针异常:

WHen i run the app i get a nullpointer exception on:

 map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map))
                .getMap();

地图=地图的ID。(机器人:ID =@ + ID /图)

The id of the map = map ( android:id="@+id/map").

为什么空指针?

推荐答案

由于您使用嵌套的片段,你应该使用getChildFragmentManager()

Since you are using nested fragments, you should use getChildFragmentManager()

SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);

和我推荐你使用getMapAsync方法,因为的GetMap是pcated德$ P $

And I recommend you to use getMapAsync method, because getMap is deprecated

mapFragment.getMapAsync(new OnMapReadyCallback() {
    @Override
    public void onMapReady(GoogleMap googleMap) {
        setupMap(googleMap);
    }
});

这篇关于在片段空指针的Andr​​oid地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆