-1

ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATON have both been included in the manifest. Also included in the Activity are:

import android.location.Location;
import android.location.LocationManager;

I have a listener for the nav drawer with the following class

private class DrawerItemClickListener implements ListView.OnItemClickListener {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null)
        {
            final double longitude = location.getLongitude();
            final double latitude = location.getLatitude();
        }

    selectItem(position);
    }
}

From this, the location = null, and thus would fail on location.getLongitude();. I can of course avoid this with if (location != null), but I want the lat and long found.

Why is the location always null?

Iorek
  • 571
  • 1
  • 13
  • 31
  • 1
    Do you target API 23 or higher? Where do you [request permission at runtime](https://developer.android.com/training/permissions/requesting.html)? – ianhanniballake Feb 11 '17 at 23:02

1 Answers1

1

Finding the location is not a easy task on the hardware side. You can't tell the device I wanna know my location so give it to me right now! It needs to observe some data from GPS satellites if outside with clear visibility, otherwise it uses other available options like wifi. Untill your device come up with a valid location, you should wait. I recommend you to observe onLocationChanged event and update your listview when this event occurs. Also it is good to use null condition untill it detect your location.

ugur
  • 3,604
  • 3
  • 26
  • 57
  • We've had heavy snowstorms for the past few days. Could this be the cause? – Iorek Feb 11 '17 at 23:05
  • Even for the best case, if u use location directly, you most probably get null data. So that s why you should wait onLocationChanged event – ugur Feb 11 '17 at 23:17
  • Yes, the solution is http://stackoverflow.com/questions/9873190/my-current-location-always-returns-null-how-can-i-fix-this. Mods jumping the gun closing it – Iorek Feb 11 '17 at 23:23
  • I also recommend FusedLocationProviderApi to get the best available solution https://developers.google.com/android/reference/com/google/android/gms/location/FusedLocationProviderApi – ugur Feb 11 '17 at 23:35