Android location error

I highlighted my problem for 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're interested

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 LastKnownLocation

But it works great if I feed it manually.

Currently, I do not know what is wrong.

+3
source share
4 answers

First, whenever you get a failure, use adb logcatDDMS or the DDMS perspective in Eclipse to get the Java stack trace associated with the failure. In this case, I suspect that you will find what you have NullPointerExceptionwhen trying to use your object location.

getLastKnownLocation() , requestLocationUpdates(), GPS. GPS .

, , getLastKnownLocation() , onLocationChanged(). , null location .

+3

, .

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();
0

- , (GPS). ACCESS_FINE_LOCATION .

0

I bet if you debug, you will see a zero exception. This is because you are trying to extract latitude and longitude from a location that has not yet been fixed. Combine this extraction with if (loc! = Null) {} and put progressDialog to keep the user there

0
source

Source: https://habr.com/ru/post/1742748/


All Articles