java – Initialize SharedPreferences from a class that does not extend activity

Question:

I am trying to make an app auto-start when the device is turned on as long as the user wants it to. To do this, I save the value of a variable using SharedPreference . The problem is that for this I use some Read and Save methods, which being in the MainActivity , must be in the MainActivity :

public class MainActivity extends Activity //implements View.OnClickListener
{
 static SharedPreferences datos;
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
(...)
 datos= getPreferences(this.MODE_PRIVATE);
(...)
    } 

public static void Guardar(String guardado, String fichero)
        {
            SharedPreferences.Editor editor=datos.edit();
            editor.putString(fichero, guardado);
            editor.commit();
        }

        public static String Leer(String fichero)
        {
            String e=datos.getString(fichero, "" );
            return e;
        }

The class in which I use the read method to know if the user has chosen the autorun option or not is the following:

 public class Monitor extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        String auto= MainActivity.Read("auto");
       if(auto.equals("true"))
       {
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
       }
    }
}

The problem is that it tries to execute the read from Monitor method at the beginning of its execution, but when trying to do this, the app stops because the data is not initialized, since it is not initialized in the method itself, but in the onCreate of the MainActivity , which has not yet been executed. However, I can't put it in the method because the method must be static to be used in other classes, so I can't pass the context to the method. On the other hand, I tried to create the Guardar() and Leer() methods in the Monitor class, but I can't either, as it gives me an error when trying to use getPreferences() .

What I can do? Is there a way to use SharedPreferences in this case? And, in case there is not, how could I store the user's decision from one execution to another?

Answer:

In a Broadcasteceiver's onReceive() method, it receives the context which you can use to get your preference:

onReceive (Context context, Intent intent)

Define within your methods, the name of the preference and instance SharedPreferences within each method:

private String PREFS_KEY = "mispreferencias";

public static void guardarValor(Context context, String keyPref, String valor) {
    SharedPreferences settings = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
    SharedPreferences.Editor editor;
    editor = settings.edit();
    editor.putString(keyPref, mostrar);
    editor.commit();
}



public static String obtenerValor(Context context, String keyPref) {
    SharedPreferences preferences = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
    return  preferences.getString(keyPref, "");
}

I suggest you use the context to call the methods, for example Read() inside your BroadcastReceiver:

obtenerValor(context, "auto");
Scroll to Top