Use the below code to store and retrive the data in SharedPreference. Your save each check box state in SharedPreference
//To get value from SharedPreference
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
boolean value = preferences.getBoolean("KEY", false);
String value = preferences.getString("KEY");
//To Save value in SharedPreference
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("KEY", value);
editor.putBoolean("KEY", value);
editor.commit();
look into it few minor changes::::
public class CheckBoxTest extends Activity implements OnCheckedChangeListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites_add_button);
CheckBox cb1,cb2,cb3,cb4;
cb1 = (CheckBox)findViewById(R.id.checkBox1);
cb1.setChecked(getFromSP("cb1"));
cb1.setOnCheckedChangeListener(this);
cb2 = (CheckBox)findViewById(R.id.checkBox2);
cb2.setChecked(getFromSP("cb2"));
cb2.setOnCheckedChangeListener(this);
cb3 = (CheckBox)findViewById(R.id.checkBox3);
cb3.setChecked(getFromSP("cb3"));
cb3.setOnCheckedChangeListener(this);
cb4 = (CheckBox)findViewById(R.id.checkBox4);
cb4.setChecked(getFromSP("cb4"));
cb4.setOnCheckedChangeListener(this);
}
private boolean getFromSP(String key){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
return preferences.getBoolean(key, false);
}
private void saveInSp(String key,boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
switch(buttonView.getId()){
case R.id.checkBox1:
saveInSp("cb1",isChecked);
break;
case R.id.checkBox2:
saveInSp("cb2",isChecked);
break;
case R.id.checkBox3:
saveInSp("cb3",isChecked);
break;
case R.id.checkBox4:
saveInSp("cb4",isChecked);
break;
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…