次のコードを使用して、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();
に値を保存するための値を取得するには//
SharedPreference
で各チェックボックスの状態を保存して、いくつかのマイナーな変更を検討::::
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;
}
}
}
は –