1

I am attempting to simply acquire the user's GPS location, but my application crashes when trying to get the latitude and longitude of the device. See code for where the error occurs..

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 
    Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    final double longitude = location.getLongitude();  //error occurs here
    final double latitude = location.getLatitude();    //and here

    LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
          // Called when a new location is found by the network location provider.
            //longitude = location.getLongitude();
            //latitude = location.getLatitude();
        }
        public void onStatusChanged(String provider, int status, Bundle extras) {}
        public void onProviderEnabled(String provider) {}
        public void onProviderDisabled(String provider) {}
      };
    //update location via GPS PROVIDER
    //can also use LocationManager.NETWORK_PROVIDER
    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

}

I am also including the ACCESS_FINE_LOCATION permission in the manifest file:

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

so I'm not quite sure why this does not work. Any help would be greatly appreciated!

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
AndroidRob
  • 27
  • 1
  • 2
  • 5
  • 1
    If you get a crash, it means you get a callstack. You may want to post it. – EboMike Feb 11 '11 at 02:41
  • Sounds like location = null, but like Mike said...we need the log. – user432209 Feb 11 '11 at 02:54
  • @EboMike @user432209 Sorry about that. I am getting a NULLPointerException. location = null. So I'm assuming that when it tries to get the user's last known location, a location is not found. Is there a better/different way to find a user's location instead of using getLastKnownLocation? – AndroidRob Feb 11 '11 at 03:24
  • You need to show the full callstack. It contains the exact line on which the problem occurs, and potentially further information. – EboMike Feb 11 '11 at 04:40

2 Answers2

2

I think you can check this StackOverflow Question: What is the simplest and most robust way to get the user's current location on Android?

Community
  • 1
  • 1
Sebastian Roth
  • 11,344
  • 14
  • 61
  • 110
0

Your error is most probably at: lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

It is because the getLastKnownLocation is a non blocking call and assuming the application has just started there is no 'last known location' that the system has. You might want to loop till you dont get a non-null value for getLastKnownLocation.

rubicon
  • 3
  • 4