How to use the SharedPreferences in a service?

1

Well my problem is this, In a service every certain amount of time I send the location and the id of the user I keep it in the SharedPreferences and when I want to get the data to send it I can not and I get this error

FATAL EXCEPTION: main
                                                                                      Process: :my_service, PID: 28490
                                                                                      java.lang.RuntimeException: Unable to instantiate service .serviciosUbicacion.servicioUbicacion: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                                          at android.app.ActivityThread.handleCreateService(ActivityThread.java:2962)
                                                                                          at android.app.ActivityThread.access$1800(ActivityThread.java:178)
                                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1553)
                                                                                          at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                                          at android.os.Looper.loop(Looper.java:194)
                                                                                          at android.app.ActivityThread.main(ActivityThread.java:5631)
                                                                                          at java.lang.reflect.Method.invoke(Native Method)
                                                                                          at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
                                                                                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
                                                                                          at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
                                                                                          at serviciosUbicacion.servicioUbicacion$LocationListener.<init>(servicioUbicacion.java:50)

THIS is my class I use for preferences

(PREFERENCIAS.java)

public class Preferencias {
    public static final String empleado = "pref_empleado";   
    public static final String NIT = "pref_NIT";
    public static final String usuario = "Pref_usuario";    
    public static final String  idUsuario="00";

    public final SharedPreferences misPreferencias;
    public boolean estaLogueado = false;

    private static Preferencias INSTANCIA;


public static Preferencias get(Context context) {
    if (INSTANCIA == null) {
        INSTANCIA = new Preferencias(context);
    }
    return INSTANCIA;
}
public    Preferencias(Context context) {
    misPreferencias = context.getSharedPreferences(empleado, Context.MODE_PRIVATE);
    estaLogueado = !TextUtils.isEmpty(misPreferencias.getString(NIT, null));
}


public boolean isLogueado(){
    return  estaLogueado;
}

}

servicioUbicacion.java

public class servicioUbicacion extends Service {
private static final String TAG = "ProyectoFinal";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 3000;
private static final float LOCATION_DISTANCE = 10f;

private class LocationListener implements android.location.LocationListener{
    Location mLastLocation;
    String ubicacion="";
    private Context mContext;
    Preferencias preff;
    int id_usuario;

    public LocationListener (String provider,Context context){
        mContext = context;
        preff = new Preferencias(mContext);
        id_usuario = preff.misPreferencias.getInt(idUsuario,0);

    }
    Retrofit retrofit = new ApiConfigRetrofit().consultas();
    apiAdapter servicioUbicacion = retrofit.create(apiAdapter.class);
    Call<resultado> altaUbicacion ;
    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG, "onLocationChanged: "+location);
        mLastLocation.set(location);
        ubicacion = String.valueOf(location.getLatitude()+","+location.getLongitude());
        altaUbicacion = servicioUbicacion.rastreo(id_usuario,ubicacion);
        altaUbicacion.clone().enqueue(new Callback<resultado>() {
            @Override
            public void onResponse(Call<resultado> call, Response<resultado> response) {
                if(response.isSuccessful()){
                    Log.d(TAG,response.body().getEstatus());
                }else{
                    Log.e(TAG,"no se inserto en la BD la ubicacion del usuario");
                }

            }

            @Override
            public void onFailure(Call<resultado> call, Throwable t) {
                Log.e(TAG,t.getMessage());
            }
        });
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.e(TAG,"onProviderChanged"+ provider);
    }

    @Override
    public void onProviderEnabled(String provider) {

        Log.e(TAG,"onProviderEnabled"+ provider);
    }

    @Override
    public void onProviderDisabled(String provider) {
        if(provider.equals("gps")){
            Log.e(TAG,"onProviderDisabled"+ provider);
        }

    }
}

LocationListener[] mLocationListeners = new LocationListener[]{
    new LocationListener(LocationManager.GPS_PROVIDER,this),
    new LocationListener(LocationManager.NETWORK_PROVIDER,this)
};

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent,int flags, int startId) {
    Log.e(TAG,"onStartComand");
    super.onStartCommand(intent,flags,startId);
    return START_STICKY;
}

@Override
public void onCreate() {
    Log.e(TAG, "onCreate");
    initializeLocationManager();

    try{
        if(mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,LOCATION_INTERVAL,LOCATION_DISTANCE,mLocationListeners[0]);
        }else{
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,LOCATION_INTERVAL,LOCATION_DISTANCE,mLocationListeners[1]);
        }
        //int id_usuario = prefss.misPreferencias.getInt(idUsuario,0);


    }catch (java.lang.SecurityException ex){
        Log.i(TAG,"Fallo la obtencion de la ubicacion, ",ex);
    }catch (IllegalArgumentException ex){
        Log.d(TAG,"Provedor de red no existe, "+ex.getMessage());
    }
    //try{
       //mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,LOCATION_INTERVAL,LOCATION_DISTANCE,mLocationListeners[0]);


    //}catch(java.lang.SecurityException ex){
    //    Log.i(TAG,"Fallo en traer la actualizacion de la ubicacion",ex);
    //}catch(IllegalArgumentException ex){
    //    Log.d(TAG,"Proveedor GPS no existe" +ex.getMessage());
    //}


}

@Override
public void onDestroy() {
    Log.e(TAG, "onDestroy");
    super.onDestroy();
    if (mLocationManager != null) {
        for (int i = 0; i < mLocationListeners.length; i++) {
            try {
                mLocationManager.removeUpdates(mLocationListeners[i]);
            } catch (Exception ex) {
                Log.i(TAG, "Fallo en remover los datos de ubicacion , ignore", ex);
            }
        }
    }
}

private void initializeLocationManager(){
    Log.e(TAG,"inicia la localizacion");
    if(mLocationManager==null){
        mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    }
}

}

FATAL EXCEPTION: main
                                                                                Process: :my_service, PID: 8506
                                                                                java.lang.RuntimeException: Unable to instantiate service serviciosUbicacion.servicioUbicacion: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
                                                                                    at android.app.ActivityThread.handleCreateService(ActivityThread.java:2962)
                                                                                    at android.app.ActivityThread.access$1800(ActivityThread.java:178)
                                                                                    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1553)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                                    at android.os.Looper.loop(Looper.java:194)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:5631)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
                                                                                 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
                                                                                    at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:170)
                                                                                    at core.Preferencias.<init>(Preferencias.java:49)
                                                                                    at a.serviciosUbicacion.servicioUbicacion$LocationListener.<init>(servicioUbicacion.java:65)
                                                                                    at.serviciosUbicacion.servicioUbicacion.<init>(servicioUbicacion.java:116)
                                                                                    at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                                    at java.lang.Class.newInstance(Class.java:1606)
                                                                                    at android.app.ActivityThread.handleCreateService(ActivityThread.java:2959)
                                                                                    at android.app.ActivityThread.access$1800(ActivityThread.java:178) 



...............................................................................................

And since from the command I call an object of the LocationListenr class and because the other methods are the ones I implement, that is why I did not put them

and I already tried this link and it did not work for me link

    
asked by JesusSh 24.10.2017 в 00:23
source

2 answers

0

If you are inside a Service, the same service is the context, therefore you can use this .

In this case one of the problems is that you should not get the preference when defining the class variables, there you can define the variables and within onCreate() get their values:

public class MyService extends Service
{


        private Context mContext;
        Location mLastLocation;
        String ubicacion="";

        //* Aquí no debes obtener los valores de las preferencias, únicamente definir las variables.
        Preferencias preff; //= new Preferencias(getApplicationContext());
        int id_usuario; = //preff.misPreferencias.getInt(idUsuario,0);

    private class LocationListener implements android.location.LocationListener{



    @Override
    public void onCreate(){

        preff = new Preferencias(getApplicationContext());
        id_usuario; = preff.misPreferencias.getInt(idUsuario,0);
        ...
        ...   
     }

    ...
public class servicioUbicacion extends Service {
private static final String TAG = "ProyectoFinal";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 3000;
private static final float LOCATION_DISTANCE = 10f;

private class LocationListener implements android.location.LocationListener{
    Location mLastLocation;
    String ubicacion="";
    private Context mContext;
    Preferencias preff;
    int id_usuario;

    public LocationListener (String provider){
         Log.e(TAG, "LocationListener " + provider);
         mLastLocation = new Location(provider);
    }
    Retrofit retrofit = new ApiConfigRetrofit().consultas();
    apiAdapter servicioUbicacion = retrofit.create(apiAdapter.class);
    Call<resultado> altaUbicacion ;
    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG, "onLocationChanged: "+location);
        mLastLocation.set(location);
        ubicacion = String.valueOf(location.getLatitude()+","+location.getLongitude());
        altaUbicacion = servicioUbicacion.rastreo(id_usuario,ubicacion);
        altaUbicacion.clone().enqueue(new Callback<resultado>() {
            @Override
            public void onResponse(Call<resultado> call, Response<resultado> response) {
                if(response.isSuccessful()){
                    Log.d(TAG,response.body().getEstatus());
                }else{
                    Log.e(TAG,"no se inserto en la BD la ubicacion del usuario");
                }

            }

            @Override
            public void onFailure(Call<resultado> call, Throwable t) {
                Log.e(TAG,t.getMessage());
            }
        });
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        Log.e(TAG,"onProviderChanged"+ provider);
    }

    @Override
    public void onProviderEnabled(String provider) {

        Log.e(TAG,"onProviderEnabled"+ provider);
    }

    @Override
    public void onProviderDisabled(String provider) {
        if(provider.equals("gps")){
            Log.e(TAG,"onProviderDisabled"+ provider);
        }

    }
}

LocationListener[] mLocationListeners = new LocationListener[]{
    new LocationListener(LocationManager.GPS_PROVIDER,this),
    new LocationListener(LocationManager.NETWORK_PROVIDER,this)
};

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent,int flags, int startId) {
    Log.e(TAG,"onStartComand");
    super.onStartCommand(intent,flags,startId);
    return START_STICKY;
}

@Override
public void onCreate() {
    Log.e(TAG, "onCreate");

    //*Obtiene preferencias.
    preff = new Preferencias(getApplicationContext());
    id_usuario; = preff.misPreferencias.getInt(idUsuario,0);

   initializeLocationManager();

    try{
        if(mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,LOCATION_INTERVAL,LOCATION_DISTANCE,mLocationListeners[0]);
        }else{
            mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,LOCATION_INTERVAL,LOCATION_DISTANCE,mLocationListeners[1]);
        }
        //int id_usuario = prefss.misPreferencias.getInt(idUsuario,0);


    }catch (java.lang.SecurityException ex){
        Log.i(TAG,"Fallo la obtencion de la ubicacion, ",ex);
    }catch (IllegalArgumentException ex){
        Log.d(TAG,"Provedor de red no existe, "+ex.getMessage());
    }
    //try{
       //mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,LOCATION_INTERVAL,LOCATION_DISTANCE,mLocationListeners[0]);


    //}catch(java.lang.SecurityException ex){
    //    Log.i(TAG,"Fallo en traer la actualizacion de la ubicacion",ex);
    //}catch(IllegalArgumentException ex){
    //    Log.d(TAG,"Proveedor GPS no existe" +ex.getMessage());
    //}


}

@Override
public void onDestroy() {
    Log.e(TAG, "onDestroy");
    super.onDestroy();
    if (mLocationManager != null) {
        for (int i = 0; i < mLocationListeners.length; i++) {
            try {
                mLocationManager.removeUpdates(mLocationListeners[i]);
            } catch (Exception ex) {
                Log.i(TAG, "Fallo en remover los datos de ubicacion , ignore", ex);
            }
        }
    }
}

private void initializeLocationManager(){
    Log.e(TAG,"inicia la localizacion");
    if(mLocationManager==null){
        mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    }
}
}
    
answered by 24.10.2017 / 01:43
source
0

Move the variables to:

- Snip -

public class servicioUbicacion extends Service {
    private static final String TAG = "ProyectoFinal";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 3000;
    private static final float LOCATION_DISTANCE = 10f;
    int id_usuario;
    String  idUsuario="00";
    private Context mContext;
    Preferencias preff;

- Snip -

Create the context in:

 public LocationListener (String provider,Context context){
            mContext = context;
 }

Then start Preferences in:

@Override
    public int onStartCommand(Intent intent,int flags, int startId) {

        preff = new Preferencias(getApplicationContext());
        id_usuario = preff.misPreferencias.getInt(idUsuario,0);

        Log.e(TAG,"onStartComand");
        super.onStartCommand(intent,flags,startId);
        return START_STICKY;
    }
    
answered by 25.10.2017 в 02:08