I have been trying to use/save the boolean value of a checkbox in other activites but haven’t had much luck.
I know you have to use SharedPreferences however I can’t set it up right. I have made a preferences class which has
private static final String OPTION_PREF = "my.main.project";
private SharedPreferences optionPreferences;
private Editor optionEditor;
private boolean checkbox;
public Preferences(Context context)
{
this.optionPreferences = context.getSharedPreferences(OPTION_PREF, Activity.MODE_PRIVATE);
this.optionEditor = optionPreferences.edit();
}
public boolean getChecked()
{
return optionPreferences.getBoolean("is_checked", checkbox);
}
public void saveChecked(boolean checkBox)
{
optionEditor.putBoolean("save_check_pref", checkBox);
optionEditor.commit();
}
And then in an options menu for example,
boolean veggieChecked;
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
Preferences pref;
pref = new Preferences(getApplicationContext());
veggieChecked = pref.getChecked();
final CheckBox checkBox = (CheckBox) findViewById(R.id.vegetarian);
if(checkBox.isChecked())
veggieChecked = true;
pref.saveChecked(veggieChecked);
I cannot really see what I am doing wrong as I am new to Android and have not used sharedpreferences before.. any help would be appreciated!
You can use something like this: