Search code examples
androidgoogle-mapsandroid-fusedlocation

Google Maps Using Fragments


I'm using google maps in fragments(Navigation Drawer). When the application starts the first fragment is shown with google maps. I've initialized the google maps in onViewCreated method. First time it shows the google maps perfectly fine with my location but when I select another fragment and come back to this fragment it throws the null pointer exception.

Exception is thrown here in the code:

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));

Method:

private void moveCamera(LatLng latLng, float zoom, String title) {
    Log.d(TAG, "moveCamera:  moving the camera to:   " + latLng.latitude + " lon " + latLng.longitude);

    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
}

OnViewCreated Method:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    getLocation();

    mapView =  view.findViewById(R.id.map);
    mapView.onCreate(savedInstanceState);
    mapView.onResume();
    mapView.getMapAsync(this);
}

OnMapReady method:

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    mMap.setMyLocationEnabled(true);
    init();
}

private void getLocation() {
    Log.d(TAG, "getDeviceLocation: getting the current device's location");
    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());

    try {
        if (mLocationGranted) {

            Task location = mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {

                    if (task.isSuccessful()) {
                        Log.d(TAG, "device location found");
                        currentLocation = (Location) task.getResult();
                        moveCamera(new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()), DEFAULT_ZOOM, "My Location");
                    } else {
                        Log.d(TAG, "onComplete:  current location is null");
                        Toast.makeText(getContext(), "unable to get current location", Toast.LENGTH_SHORT).show();
                        getLocationPermissions();

                    }
                }
            });
        }

    } catch (SecurityException e) {
        Log.e(TAG, "SecurityException :  " + e.getMessage());
    }


}

Error

Exception: java.lang.NullPointerException: Attempt to invoke virtual method 
void com.google.android.gms.maps.GoogleMap.moveCamera(com.google.android.gms.map.CameraUpdate) 
on a null object reference`

Solution

  • You are getting a NullPointerException because your map is not ready when you are trying to move its camera.

    You can try to do the following

    @Override
    public void onMapReady(GoogleMap googleMap) {
    
      mMap = googleMap;
      mMap.setMyLocationEnabled(true);
      init();
    
      getLocation();
    
    }
    

    by doing that, your code will just attempt to move the maps camera when the map is available or change your code logic and remove your moveCamere() from the getLocation() method and for example put it in onResume()