This question already has an answer here:
I'm trying to get the user location with location manager but the location always returns null. I also am asking to the user to turn on the gps.
This is my code:
int permisioncheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
if(permisioncheck == 0){
lm = (LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location location = lm.getLastKnownLocation(provider);
if (location == null) {
continue;
}
if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = location;
}
}
if(bestLocation == null){
System.out.println("is NULL!");
}
}else{
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
I hope that someone could help me to find the error, thanks.
The "error" is that you are assuming that
getLastKnownLocation()
will return aLocation
. Frequently, it will returnnull
. UsegetLastKnownLocation()
as a possible optimization, but otherwise you need torequestLocationUpdates()
, then use the location in theonLocationChanged()
method.See this sample project and the documentation for more.