0

I'm trying to obtain my current location via GPS, but nothing seems to work, I followed many questions here but with little results...

Here's my code:

private GeoPoint getActualPosition()
{
    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

    Location current = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    actualLat = (int)(current.getLatitude()*1E6);
    actualLong = (int)(current.getLongitude()*1E6);

    GeoPoint point = new GeoPoint(actualLat, actualLong);

    return point;
}

Now, the "this" part of the method (on requestLocationUpdates) makes reference to the activity who implements the LocationListener interface, where its onLocationChanged method is:

@Override
public void onLocationChanged(Location location) {
    actualLat = (int)(location.getLatitude()*1E6);
    actualLong = (int)(location.getLongitude()*1E6);

}

My problem is on the current Location line, where "current" is always, always null, and I can't find why.

My manifest has the permissions needed:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

So I don't really know what is wrong with my code.

Thank you for your time!!

BrunoJ
  • 226
  • 2
  • 13
  • 2
    Welcome to stackoverflow. If you find a particular answer helpful, please upvote it. If you find a particular answer to be right, please accept it. – Kurtis Nusbaum Oct 20 '11 at 03:48

3 Answers3

2

getLastKnownLocation() returns the last cached location. If there was no such location will return null (for e.g if the phone is turned off) If the provider is currently disabled, null is returned

Getting a GPS fix takes time. onLocationChanged() will be called only after getting a proper fix, this time may range from 20 seconds to a few minutes.

Only after onLocationChanged() is called at least once, will getLastKnownLocation() return the last valid location.

Reno
  • 33,594
  • 11
  • 89
  • 102
1

are you running the app / your code on an emulator or a physical device ? If its an emulator and you never set the location before (using DDMS view inside eclipse), the location will be null.

hope this helps.

Ahsan
  • 2,964
  • 11
  • 53
  • 96
0

According to the documentation for getLastKnownLocation:

If the provider is currently disabled, null is returned.

So if you don't have GPS enabled on the device you're testing this on, you're going to get null. If you're using the android emulator, please see this stackoverflow post to see how to emulate a particular location.

Community
  • 1
  • 1
Kurtis Nusbaum
  • 30,445
  • 13
  • 78
  • 102