getLastKnownLocation returns null
You are trying to get the cached location from the Network Provider. You have to wait for a few minutes till you get a valid fix. Since the Network Provider's cache is empty, you are obviously getting a null there..
Use this method to get the last known location:
LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();
private Location getLastKnownLocation() {
mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
List<String> providers = mLocationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = mLocationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
return bestLocation;
}
you are mixing the new and the old location API's together when you shouldnt.
to get the last known location all your have to do is call
compile "com.google.android.gms:play-services-location:11.0.1"
mLocationClient.getLastLocation();
once the location service was connected.
read how to use the new location API
http://developer.android.com/training/location/retrieve-current.html#GetLocation
private void getLastLocationNewMethod(){
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// GPS location can be null if GPS is switched off
if (location != null) {
getAddress(location);
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d("MapDemoActivity", "Error trying to get last GPS location");
e.printStackTrace();
}
});
}