0

I would have thought that requesting the "lastKnownLocation" would return a saved coordinate (GeoPoint) that points to the last known location of the device (from when it last had access to the GPS functionalities).

According to some tests (made on OSMDroid's GpsMyLocationProvider), it seems like requesting that location returns a NullPointer.

    GpsMyLocationProvider provider = new GpsMyLocationProvider(MainActivity.mainActivity);
    provider.addLocationSource(LocationManager.NETWORK_PROVIDER);
    locationOverlay = new MyLocationNewOverlay(provider, map);

I've been trying to set up default GeoPoint for centering the map when it is first launched, and then recentering the map where the GPS now has confirmed a position.

The problem is that provider.getLastKnownLocation() returns a NullPointer exception unless it is given time to actually get the current location from the GPS.

What am I getting wrong here? Shouldn't the "last known location" be a GeoPoint that is saved in memory on the phone and always have something there, unless the phone never ever had access to GPS localization ?

payne
  • 4,691
  • 8
  • 37
  • 85

1 Answers1

0

Please see https://developer.android.com/training/location/retrieve-current

You must set the permissions correctly too. Note that at the bottom they describe why the location may be null so see these for troubleshooting.

If you're using an emulator see How to emulate GPS location in the Android Emulator?

Thomas
  • 320
  • 2
  • 6
  • For permissions, I've seen that indeed it can be tricky. As it is now, on my API level 22 Android phone, everything goes fine. But for my friend, which has a level 25, his phone crashes if he does not give permission to the app to access GPS. **Also**, this doesn't really answer my question: based on my tests, the "getLastKnownLocation" only works once the GPS is activated and has found out your location at the current moment. – payne Aug 01 '18 at 23:09
  • 1
    The first link lists 3 reasons the location may return null. Have you checked for those 3 situations? – Thomas Aug 06 '18 at 19:14
  • Ah! `Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.` Seems like that could very well be the problem. But who leaves its "Location" open when not needed anyways? It would just waste battery and data. Saving the last known location in the memory instead of the cache barely takes any space: that's 2 real numbers... – payne Aug 07 '18 at 17:10