I am using simple location manager object to get lastKnownLocation() of device
but getting null object in
before get last location, maybe you want get current location, check if null or have. if not set last loccation if you want use FusedLocationProviderClient and before use it adding this:
implementation 'com.google.android.gms:play-services-location:16.0.0'
on your build.gradle(Module: app), and call method zoomMyCuurentLocation() whean activity create.
private void zoomMyCuurentLocation() {
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
}
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null) {
double lat = location.getLatitude();
double longi = location.getLongitude();
LatLng latLng = new LatLng(lat,longi);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14.f));
Log.d(TAG, "zoomMyCuurentLocation: location not null");
} else {
setMyLastLocation();
}
}
private void setMyLastLocation() {
Log.d(TAG, "setMyLastLocation: excecute, and get last location");
FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
fusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener() {
@Override
public void onSuccess(Location location) {
if (location != null){
double lat = location.getLatitude();
double longi = location.getLongitude();
LatLng latLng = new LatLng(lat,longi);
Log.d(TAG, "MyLastLocation coordinat :"+latLng);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14.f));
}
}
});
}