Error with gps android
-
28-10-2019 - |
문제
I have a GPS error in my app when I am trying to get my current location, by gps or by network
private static LocationManager lm;
private static LocationListener locationListener;
private static Location posicion;
private double latitud;
private double longitud;
posicion = ObtenPosicion();
latitud = posicion.getLatitude();
longitud= posicion.getLongitude();
//Me centro en el mapa
final GeoPoint yo = new GeoPoint((int)(latitud),(int)(longitud));
public Location ObtenPosicion(){
if (lm == null)
{
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocListener();
if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
lm.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
LOCATION_UPDATE_TIME,
LOCATION_UPDATE_DISTANCE,
locationListener);
posicion = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
LOCATION_UPDATE_TIME,
LOCATION_UPDATE_DISTANCE,
locationListener);
posicion = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
return posicion;
}
private class LocListener implements LocationListener
{
@Override
public void onLocationChanged(Location loc) {
posicion.set(loc);
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
}
public static Location getCurrentLocation ()
{
return posicion;
}
public void stopLocationListening ()
{
if (lm != null)
lm.removeUpdates(locationListener);
}
The error is a nullpointerexception in a line :
12-06 17:04:25.418: E/AndroidRuntime(4744): java.lang.NullPointerException
12-06 17:04:25.418: E/AndroidRuntime(4744): at com.rbrlnx.lugares.editarLugar$LocListener.onLocationChanged(editarLugar.java:215)
I tried with a different codes but its me impossible..
해결책
Your issue is with the fact that you did not allocate a 'posicio' object. You simply declared it as static. So, when you get the callback from the system in the onLocationChanged callback you try to use a null object.
In your onCreate method, you need to allocate and initialize the posicion with:
posicion = new Location();
다른 팁
The posicion variable is null here.... Initialize it try any/both of the two
In onCreate()
method, initialize posicion with a default value. And/or than call ObtenPosicion()
at appropriate place with try/catch if necessary
제휴하지 않습니다 StackOverflow