I am implementing a location android app , using fused location provider client .It has been working few days ago but actually it craches because it is returning as value null and here is what i got as error message : java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference . How could i figure it out? Here is the code i have implemented :
fusedLocationProviderClient.getLastLocation()
.addOnSuccessListener(baseView, position -> {
Log.d("TAG", "updateGPS: position elements are : " + "lon = " + position.getLongitude() + "lat = " + position.getLatitude() + "alt " + position.getAltitude() + "Acc= " + position.getAccuracy() + " Speed = " + position.getSpeed());
if (position.getAccuracy() <= 20f) {
location.setLongitude(position.getLongitude());
location.setLatitude(position.getLatitude());
location.setAltitude(position.getAltitude());
location.setAccuracy(position.getAccuracy());
location.setSpeed(position.getSpeed());
}
here is my callback method :
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(@NonNull LocationResult locationResult) {
super.onLocationResult(locationResult);
Location location = locationResult.getLastLocation();
assert location != null;
Log.d("TAG", "onLocationResult: callback method " + "longitude " + location.getLongitude() + "latitude " + location.getLatitude() + "Accuracy " + location.getAccuracy() + "Speed " + location.getSpeed());
}
};
and here is the update settings :
public void locationSettings() {
//Put in the time service
newlocationRequest = new LocationRequest();
newlocationRequest.setInterval(30000);
newlocationRequest.setFastestInterval(5000);
//most accurate use GPS
newlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
startLocationUpdate();
}
and finally here is the update function :
public void startLocationUpdate() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
fusedLocationProviderClient.requestLocationUpdates(newlocationRequest, locationCallback, Looper.myLooper());
// updateGPS();
}