Skip to content Skip to sidebar Skip to footer

Getting Java.lang.nullpointerexception In Mapfragment

I am using GoogleMaps in my application. For that purpose, I have implemented SupportMapFragment Map-v2 in my custom Fragment class. But unfortunately I am getting NullPointerExcep

Solution 1:

I got the same issue long back when I was newly working with maps. The issue is because it takes time for google map to load ( if you're using inside a fragment, you can expect this load time to be huge) and when you try to access map before it is being loaded, you'll get NullPointerException saying map reference went null. You should wait for the map to load first and then you should access the map views. You have pre-defined callback for that and here is how you should use it.

supportMapFragment.getMapAsync(new OnMapReadyCallback() {

        @Override
        public void onMapReady(GoogleMap map) {

            googleMap = map; 
        googleMap.setMapType (GoogleMap.MAP_TYPE_NORMAL);
        googleMap.setOnMarkerClickListener(this);
        googleMap.setMyLocationEnabled(true);

            for(int i=0;i<mList.size ();i++){
                drawMarker (new LatLng (Double.parseDouble (mList.get (i).getLatitude ()), Double.parseDouble (mList.get (i).getLongitude ())),i);
            }

        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target (new LatLng (Double.parseDouble ("13.0900"), Double.parseDouble ("80.2700")))
                .zoom (7)                              
                .build ();                   


        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition (cameraPosition), new GoogleMap.CancelableCallback () {

            @Override
            public void onFinish() {
                CameraUpdate cu_scroll = CameraUpdateFactory.scrollBy(-300, 70);
                googleMap.animateCamera(cu_scroll);
            }

            @Override
            public void onCancel() {
            }
        });
        }
    });

Post a Comment for "Getting Java.lang.nullpointerexception In Mapfragment"