Can Not Save The State Of Checkbox In Android
I am developing an application. There are many checkbox in one page. I want to save the state of CheckBox when I exit page. I use SharedPreferrences to save. The code is like this:
Solution 1:
You are saving vallues but you have to restore them you your activity is started like this :
SharedPreferencesprefs= getSharedPreferences("syllabus", 0);
checkbox1.setChecked(prefs.getBoolean("cbx1_ischecked" ,false));
checkbox2.setChecked(prefs.getBoolean("cbx2_ischecked" ,false));
Solution 2:
try this
boolean check1,check2;
checkbox1.setOnCheckedChangeListener(newOnCheckedChangeListener(){
publicvoidonCheckedChanged(CompoundButton arg0, boolean isChecked) {
// TODO Auto-generated method stub
check1=isChecked;
}
});
checkbox2.setOnCheckedChangeListener(newOnCheckedChangeListener(){
publicvoidonCheckedChanged(CompoundButton arg0, boolean isChecked) {
// TODO Auto-generated method stub
check2=isChecked;
}
});
//store boolean only once when you leave the activityEditoreditor= getSharedPreferences("syllabus", 0).edit();
editor.putBoolean("cbx1_ischecked", check1);
editor.putBoolean("cbx2_ischecked", check2);
editor.commit();
In onCreate()SharedPreferencesprefs= getSharedPreferences("syllabus", 0);
checkbox1.setChecked(prefs.getBoolean("cbx1_ischecked" ,false));
checkbox2.setChecked(prefs.getBoolean("cbx2_ischecked" ,false));
Post a Comment for "Can Not Save The State Of Checkbox In Android"