Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting null from 'getLastKnownLocation' on SDK

Tags:

android

I have a problem related to the Location API.

I tried the following code:

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);

loc is always null, when getLastKnownLocation() is called.

What is wrong?

like image 768
AndroiDBeginner Avatar asked Dec 16 '09 18:12

AndroiDBeginner


2 Answers

Along with the permissions in your AndroidManifest.xml file, have you registered a location listener?

LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location loc = getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates(LocationManager.GPS, 100, 1, locationListener); 

Then have a method, in this case locationListener, to complete your task

private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
}
like image 52
Anthony Forloney Avatar answered Oct 16 '22 12:10

Anthony Forloney


If you're running the code in the emulator, any calls to get the GPS location will return null until you explicitly update the location (via Eclipse or ADB).

like image 43
Erich Douglass Avatar answered Oct 16 '22 13:10

Erich Douglass