Chris Stryker
Chris Stryker

Reputation: 1058

Android Location Error

I've singled out my problem to a few lines of code

lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 5.0f, this);
lat = location.getLatitude();
lng = location.getLongitude();
//lat = new Double(40.431682);
//lng = new Double(-74.2021819);
pLocation = new GeoPoint((int)(lat * 1000000), (int)(lng * 1000000));

My onLocationChanged if you were wondering

public void onLocationChanged(Location location) {
        if (location != null) {
        lat = location.getLatitude();
        lng = location.getLongitude();
        pLocation = new GeoPoint((int)(lat * 1000000), (int)(lng * 1000000));
        }
}

My application crashes if I try to get the LastKnownLocation

But it works fine if I feed it a Location manually

I have no idea currently whats wrong

Upvotes: 3

Views: 1896

Answers (4)

Max Ch
Max Ch

Reputation: 1257

I bet if you debug you'll see null exception. So it happens because you're trying to extract latitude and longitude from location which isn't fix yet. Surround this extraction with if (loc!=null) {} and put progressDialog to hold user there

Upvotes: 0

Fedor
Fedor

Reputation: 43422

This may happen because fine location (GPS) is not enabled on your device. Or ACCESS_FINE_LOCATION permission is not specified in your manifest.

Upvotes: 0

Chris Stryker
Chris Stryker

Reputation: 1058

My fix was basically to just use coarse location.

Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
String bestProvider = lm.getBestProvider(criteria, true);
Location loc = lm.getLastKnownLocation(bestProvider);
lat = loc.getLatitude();
lng = loc.getLongitude();

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007534

First, whenever you get a crash, use adb logcat, DDMS, or the DDMS perspective in Eclipse to get the Java stack trace associated with the crash. In this case, I suspect you will find that you have a NullPointerException when attempting to use your location object.

You cannot use getLastKnownLocation() until well after you call requestLocationUpdates(), particularly for GPS. It may take tens of seconds for GPS to start providing fixes.

Please alter your code to eliminate your use of getLastKnownLocation() and just use the logic needing the location already in your onLocationChanged() method. At minimum, look for a null location object and don't try to use it.

Upvotes: 3

Related Questions