Google Maps Fragment returning null inside a fragment

前端 未结 8 883
花落未央
花落未央 2020-11-27 18:05

So I have an empty fragment that contains a map fragment. Whenever I try to activate the fragment containing the map, my app crashes and returns a null pointer error on this

8条回答
  •  攒了一身酷
    2020-11-27 18:49

    I can face same problem but finally i can solve that error.Now Map is Properly showing...

    => Call initilizeMap() Method in Fragment within a onCreateView() method...

    => Declare Global Variable like ,

    private GoogleMap googleMap;
    
     private void initilizeMap() {
        try {
    
            // Changing marker icon
            // marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.my_marker_icon)));
    
            // adding marker
            if (googleMap == null) {
                googleMap = ((MapFragment)getActivity().getFragmentManager()
                        .findFragmentById(R.id.map)).getMap();
    
                // create marker
                MarkerOptions marker = new MarkerOptions().position(
                        new LatLng(latitude, longitude)).title(
                        "YourCare");
    
                // Changing marker icon
                MarkerOptions icon = marker.icon(BitmapDescriptorFactory
                        .defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
                // adding marker
    
                LatLng latLng = new LatLng(latitude, longitude);
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
                        latLng, 15);
                googleMap.animateCamera(cameraUpdate);
                // locationManager.removeUpdates(this);
    
                googleMap.addMarker(marker);
                googleMap.setMyLocationEnabled(true);
                // check if map is created successfully or not
                if (googleMap == null) {
                    Toast.makeText(getActivity(),
                            "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                            .show();
                }
    
            }
        } catch (Exception e) {
            System.out.print("Error :" + e.getMessage());
        }
    
    }
    

提交回复
热议问题