Error con gps android
-
28-10-2019 - |
Pregunta
Tengo un error de GPS en mi aplicación cuando intento obtener mi ubicación actual, por gps o por red
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);
}
El error es una excepción de punto nulo en una línea:
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)
Intenté con códigos diferentes pero es imposible ...
Solución
Su problema es el hecho de que no asignó un objeto 'posicio'.Simplemente lo declaró como estático.Entonces, cuando recibe la devolución de llamada del sistema en la devolución de llamada onLocationChanged, intenta usar un objeto nulo.
En su método onCreate, debe asignar e inicializar la posición con:
posicion = new Location();
Otros consejos
La variable de posición es nula aquí ... Inicialice, intente cualquiera / ambos de los dos
En el método onCreate()
, inicialice la posición con un valor predeterminado.Y / o llamar a ObtenPosicion()
en el lugar apropiado con try / catch si es necesario