How To Save Checkbox Value With Shared Preferences?
I don't know why my code not save checkbox checked value; if I check checkbox and after I click on another tab and comeback to previous tab, checkbox is not selected...I hope that
Solution 1:
You can store boolean values on shared preferences. Here's an example.
SharedPreferences myPrefs;
SharedPreferences.Editor myPrefsPrefsEditor;
staticfinalStringMY_SHARED_PREF="name_of_your_shared_pref";
Initialize your shared preferences
myPrefs = this.getSharedPreferences(MY_SHARED_PREF, Context.MODE_PRIVATE);
Store your values using the following.
myPrefsPrefsEditor = myPrefs.edit();
myPrefsPrefsEditor.putBoolean(key, value);
myPrefsPrefsEditor.commit();
key = use to find the value from shared pref
value = the value you want to store
This is how your read your values
myPrefs.getBoolean(key, defaultValue);
key = the key of the value you want to get
defaultValue = the default value when there's no value for the given key.
Hope this helps.
Solution 2:
@OverridepublicvoidafterTextChanged(Editable s) {
p.setQuantità(finalHolder.edit.getText().toString().trim());
SharedPreferencespreferences= getContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editoreditor= preferences.edit();
editor.putString("KEY", finalHolder.edit.getText().toString().trim());
editor.putBoolean("CheckBox_Value", finalHolder.chkBox.isChecked());
editor.commit();
}
and then retrieve it using getBoolean as you have already done
Solution 3:
@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkBox = (CheckBox) findViewById(R.id.checkBox1);
SavedPreferences();
}
privatevoidsavePreferences(boolean value) {
SharedPreferencessharedPreferences= PreferenceManager
.getDefaultSharedPreferences(this);
Editoreditor= sharedPreferences.edit();
editor.putBoolean(value);
editor.commit();
}
publicclassactivity2extendsfragment{
public onCreateView extendsFragment {
SharedPreferencessharedPreferences= PreferenceManager
.getDefaultSharedPreferences(this);
booleancheckBoxValue= sharedPreferences.getBoolean("CheckBox_Value", false);
if (checkBoxValue) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
}
}
Post a Comment for "How To Save Checkbox Value With Shared Preferences?"