空对象引用android

时间:2018-07-23 23:31:22

标签: android google-maps firebase-realtime-database nullpointerexception marker

我正在创建一个在地图上显示标记的应用程序。问题是运行我的应用程序时出现以下错误:

 java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
    at com.flag.app.app.fragment.FragmentMap$1.onMapReady(FragmentMap.java:186)
    at com.google.android.gms.maps.zzac.zza(Unknown Source)
    at com.google.android.gms.maps.internal.zzaq.onTransact(Unknown Source)
    at android.os.Binder.transact(Binder.java:380)

这是我的FragmentMap.class

公共类FragmentMap扩展了片段{

private GoogleMap googleMap;
public MapView mMapView;

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

    mMapView =  rootView.findViewById(R.id.mapView);
    mMapView.onCreate(savedInstanceState);

    mMapView.onResume(); // needed to get the map to display immediately

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

    mMapView.getMapAsync(new OnMapReadyCallback() {
        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onMapReady(GoogleMap mMap) {
            googleMap = mMap;
            Log.d("debug", "map ready called");
            LatLng lviv = new LatLng(49.838, 24.029);
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lviv, 12));
            if (ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                Log.d("debug", "problem");

            }

            List<Marker> markerList = getActivity().getIntent().getParcelableArrayListExtra(EXTRA_MARKER_LIST);
            for (int i = 0; i < markerList.size(); i++) {
                Marker marker = markerList.get(i);
                Location location = marker.getLocation();
                clusterManager.setItems(markerList);
            }
        }

    });

    return rootView;
}

这是我的数据库屏幕: database

1 个答案:

答案 0 :(得分:0)

您的问题,因为markerList的值为NULL

您不应使用这种方式:

List<Marker> markerList = getActivity().getIntent().getParcelableArrayListExtra(EXTRA_MARKER_LIST);

因为片段的目的是重复使用。

您应该为此片段创建一个构造函数,并按如下所示传递任何内容:

 public static MapFragment newInstance(List<Marker> markers) {
        MapFragment mapFragment = new MapFragment();
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("EXTRA_MARKER_LIST", markers);
        mapFragment.setArguments(bundle);
        return mapFragment;
    }

并且请确保 Marker已经实施Parcelable

希望这会有所帮助