androidgoogle-mapsfusedlocationproviderapicurrentlocation

Give java.lang.NullPointerException: when i click on current location button


when i click on current button for getting user's current location then give nullpointer exception even i check the fusedapi is granted or not and also when user allow for current location access then i retrive the current location but it show the error

MapFragment

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

    latlng.add(new LatLng(22.32371, 73.16409));
    latlng.add(new LatLng(22.32737, 73.17566));
    latlng.add(new LatLng(22.28, 73.1903696));
    latlng.add(new LatLng(22.334, 73.21853));
    latlng.add(new LatLng(22.40303, 73.22369));
    latlng.add(new LatLng(22.55148, 72.97035));

    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);  //use SuppoprtMapFragment for using in fragment instead of activity  MapFragment = activity   SupportMapFragment = fragment
    mapFragment.getMapAsync(this);


    askPermission();
    createGoogleApi();

    mbtn = rootview.findViewById(R.id.myLocationButton);
    mbtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getcurrentmarker();
        }
    });

    return rootview;
}


@Override
public void onMapReady(GoogleMap googleMap)
{
    mgoogleMap = googleMap;
    mgoogleMap.setOnMarkerClickListener(this);
}

@Override
public void onStart() {
    super.onStart();
    // Call GoogleApiClient connection when starting the Activity
    googleApiClient.connect();
}


@Override
public void onStop() {
    super.onStop();

    // Disconnect GoogleApiClient when stopping Activity
    googleApiClient.disconnect();
}


private void createGoogleApi()
{
    Log.d(TAG, "createGoogleApi()");
    if ( googleApiClient == null )
    {
        googleApiClient = new GoogleApiClient.Builder( getContext() )
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener( this )
                .addApi(LocationServices.API)
                .build();
    }
}


// Check for permission to access Location
private boolean checkPermission() {
    Log.d(TAG, "checkPermission()");
    // Ask for permission if it wasn't granted yet
    return (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED );
}

// Asks for permission
private void askPermission() {
    Log.d(TAG, "askPermission()");

    ActivityCompat.requestPermissions(
            MapFragment.super.getActivity(),
            new String[] { Manifest.permission.ACCESS_FINE_LOCATION },
            REQ_PERMISSION
    );
}

// Verify user's response of the permission requested
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == REQ_PERMISSION) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(getContext(), "Permission", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getContext(), "Permission DENIED", Toast.LENGTH_SHORT).show();
        }
    }
}


// App cannot work without the permissions
private void permissionsDenied() {
    Log.w(TAG, "permissionsDenied()");

}


// Start location Updates
private void startLocationUpdates(){
    Log.i(TAG, "startLocationUpdates()");
    locationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(6000)
            .setFastestInterval(5000);
    //movement in meter

    if ( checkPermission() )
        LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
}

@Override
public void onLocationChanged(Location location) {
    Log.d(TAG, "onLocationChanged ["+location+"]");
    lastLocation = location;
    writeActualLocation(location);
}


@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.i(TAG, "onConnected()");
    getLastKnownLocation();
}

// GoogleApiClient.ConnectionCallbacks suspended
@Override
public void onConnectionSuspended(int i) {
    Log.w(TAG, "onConnectionSuspended()");
}

// GoogleApiClient.OnConnectionFailedListener fail
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.w(TAG, "onConnectionFailed()");
}

// Get last known location
private void getLastKnownLocation() {
    Log.d(TAG, "getLastKnownLocation()");
    if ( checkPermission() ) {
        lastLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if ( lastLocation != null ) {
            Log.i(TAG, "LasKnown location. " +
                    "Long: " + lastLocation.getLongitude() +
                    " | Lat: " + lastLocation.getLatitude());
            writeLastLocation();
            startLocationUpdates();
        } else {
            Log.w(TAG, "No location retrieved yet");
            startLocationUpdates();
        }
    }
    else askPermission();
}

private void writeActualLocation(Location location)
{
        lastLocation = location;
        showmarker(latlng);
}

private void writeLastLocation() {
    writeActualLocation(lastLocation);
}



private void getcurrentmarker()
{
    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mgoogleMap.setMyLocationEnabled(true);
    mgoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
    mgoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()), 14));
}

private void showmarker(List<LatLng> positions)
{
    Log.d(TAG,"show");
    if(!markers.equals(null))
    {
        markers.clear();
    }
    if ( marker != null ) {
        marker.remove();
    }
    for (LatLng position : positions) {
        Marker marker = mgoogleMap.addMarker(
                new MarkerOptions()
                        .position(position)
                        .visible(false)); // Invisible for now
        markers.add(marker);
    }

    for (Marker marker : markers) {
        if (SphericalUtil.computeDistanceBetween(new LatLng(lastLocation.getLatitude(),lastLocation.getLongitude()), marker.getPosition()) < 400) {
            marker.setVisible(true);
            float zoom = 14f;
            CameraUpdate cameraUpdate1 = CameraUpdateFactory.newLatLngZoom(marker.getPosition(), zoom);
            mgoogleMap.animateCamera(cameraUpdate1);
        }
    }

}

@Override
public boolean onMarkerClick(Marker marker)
{
    BottomSheetFragment bottomSheetFragment = new BottomSheetFragment(lastLocation,marker.getPosition());
    bottomSheetFragment.show(getFragmentManager(), bottomSheetFragment.getTag());
    return false;
}

}

Manifest

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

before getting googleapiclient connected i ask the permission for current location then i retrive current location and after i click the current location button

logcat

java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
    at com.example.eats.Fragment.MapFragment.getcurrentmarker(MapFragment.java:256)

Solution

  • Check for location is enabled/ disabled state If location is disabled then result will be null.