I am trying to get an app to start automatically when the device is turned on as long as the user wants. To do this, I save the value of a variable using SharedPreference
. The problem is that for this I use Read and Save methods, that being in MainActivity
, must be in 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 is the method of reading to know if the user has chosen or not the auto-start option 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 method from Monitor
when starting its execution, but when trying to do this, the app stops because data is uninitialized, since it is not initialized in the method itself, but in the onCreate
of MainActivity
, which has not yet been executed. However, I can not put it in the method because it must be static to be able to use it in other classes, so I can not 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 not either, since I get an error when trying to use getPreferences()
.
What can I do? Is there any way to use SharedPreferences
in this case? And, in case there is not, how could you store the user's decision from one execution to another?