使用以下代码在 SharedPreference 中存储和检索数据。您在 SharedPreference 中保存每个复选框状态
//从SharedPreference中获取值
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
boolean value = preferences.getBoolean("KEY", false);
String value = preferences.getString("KEY");
//在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();
看看它的一些小的变化::::
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;
}
}
}