Reputation: 191
I have been trying to get current location data using FusedLocationProviderClient in android. I always get null on the location variable, How do i fix it?
I have tried to follow the steps from android developer website for FusedLocationProviderClient, It didn't help.
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "Location permission Required", Toast.LENGTH_SHORT).show();
} else {
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
mLocation = location;
Log.d(TAG, "getLocation: "+mLocation.getLatitude()+","+mLocation.getLongitude());
}
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(20 * 1000);
locationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult == null) {
return;
} else {
for (Location location : locationResult.getLocations()) {
if (location != null) {
mLocation = location;
Log.d(TAG, "getLocation: "+mLocation.getLatitude()+","+mLocation.getLongitude());
}
}
}
}
};
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "No Location Permission", Toast.LENGTH_SHORT).show();
}
else {
mFusedLocationClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}}
});
I expect this code to return current location data.
Upvotes: 0
Views: 1742
Reputation: 3190
The getLastLocation()
returns null if the Android System
doesn't have a knowledge about its last location.To provide last location to the System
you can try one of the following things:
Before opening your app, open Google Maps and let the device get the current location.After that you can return to your app.
The Location
service in Android
provide 3 modes.Check-up the High
Accuracy mode. Go to Setting -> Location -> High Accuracy Mode.
Upvotes: 0
Reputation: 93708
There's nothing to fix, this is expected behavior. getLastLocation returns the last location IF THE SYSTEM KNOWS IT. It almost never knows it. So it will almost always return null. If you want to get an assured location, use requestLocationUpdates. But you can never rely on getLastLocation working, and even when it does the data may be old. It should really only be used in very limited circumstances.
Upvotes: 1