0

I am getting a null location when setting the longitutde and lattitude. I am not sure what I am doing wrong. I debugged this code with Location Services turned on and off. When they were on, the GPS_PROVIDER if statement would be true, and when they were off it neither of the conditions would be true and it would go to the else statement. However even when it confirmed the provider was enabled, the call to getLastKnownLocation returned null. Any ideas as to why?

private void setCoordinates(Context context) {
    LocationManager lm = (LocationManager) context
            .getSystemService(Context.LOCATION_SERVICE);
    Location location = null;
    if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    } else if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        location = lm
                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        longitude = location.getLongitude();
        latitude = location.getLatitude();
    } else {
        Log.e("AlarmLocation", "unable to get location");
    }
9er
  • 1,604
  • 3
  • 20
  • 37
  • 1
    possible duplicate of [getLastKnownLocation() returns null even with best provider](http://stackoverflow.com/questions/15409754/getlastknownlocation-returns-null-even-with-best-provider) – Steve Benett Mar 25 '14 at 22:35
  • see related answer: http://stackoverflow.com/a/1916986/2399024 – donfuxx Mar 25 '14 at 22:37
  • 1
    There is no guarantee that there is a last known location for any provider... if you checked both and both return null then you have no last known location. In that case you have no choice but to register a callback and wait until one of them gives you a location fix. – Bob Mar 26 '14 at 00:06
  • Are you trying to get the current location? Then use LocationClient – Libin Mar 26 '14 at 01:41

0 Answers0