tags:

views:

361

answers:

4

I am facing with 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 call getLastKnownLocation().

What is wrong?

+1  A: 

Have you set the permissions in your AndroidManifest.xml? You need these permissions in order to access the user's location with an application:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
Daniel Lew
A: 

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).

Erich Douglass
A: 

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();
}
Anthony Forloney
A: 

Thanks guys.

I've set the permissions :

<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

I need to get location on 2 activities.

So, Do I need declare on both following listener ?

private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
}

Thanks in advance.

AndroiDBeginner
yeah, you would need to declare a listener, such as locationListener, to both of your activities.
Anthony Forloney