I have a method to show on the map the current position of the device. I am using FusedLocationProviderClient
because it seems to be the most accurate.
On currentLocation.getLatitude()
I get the warning:
Method invocation may produce java.Lang.NullPointerException
How can I avoid this risk? And why it is related only to currentLocation.getLatitude() and not to currentLocation.getLongitude()
?
private void getDeviceLocation(){
Log.d(TAG, "getDeviceLocation: getting the devices current location");
FusedLocationProviderClient mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
try{
if(mLocationPermissionsGranted){
final Task location = mFusedLocationProviderClient.getLastLocation();
location.addOnCompleteListener(task -> {
if(task.isSuccessful()){
Log.d(TAG, "onComplete: found location!");
Location currentLocation = (Location) task.getResult();
LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM));
}else{
Log.d(TAG, "onComplete: current location is null");
}
});
}
}catch (SecurityException e){
Log.e(TAG, "getDeviceLocation: SecurityException: " + e.getMessage() );
}
}