私の理解が正しければ、SharedPreferences と SQLiteDatabase の両方を使用して同じデータを永続化/保存する PreferenceActivity があるようです。PreferenceActivity は、データ入力用に設計された事前構築済みの ListView のように見えますが、実際にはさらに多くの機能を備えています。PreferenceActivity は、アプリケーションに割り当てられ、Android OS によって管理される特別なデータストアである SharedPreferences に環境設定を自動的に保存および読み込みます。
設定を保存することを目的としていますが、必要に応じて SharedPreferences を使用して一部のデータを保持できます。環境設定を介して自動的に、またはエディターを呼び出して手動で。設定サブクラスを作成して動作を置き換える、OnPreferenceChangeListener を使用して動作を変更する、または setPersistent(boolean) への呼び出しを介して永続性を切り替えるなど、さまざまな方法でこの永続性を中断および/または変更できます。
この方法で PreferenceActivity を使用する代わりに、AdapterView または ListActivity を使用してアクティビティを作成し、SimpleCursorAdapter を使用してビューへのデータのバインドを自動化することができます。
PreferenceActivity での SharedPreferences への変更の永続化に関する質問に答えるために、大まかに概要を説明したサンプル コードをいくつか提供し、いくつかの潜在的な問題点を概説しました。プロジェクトに適応するのがそれほど難しくないはずの明確な(冗長ではあるが)方法で、何が必要でどこにあるのかという考えを与えるほど、使用可能なソリューションを表すことは意図されていません。
/* Preference value modification example.
* This is a code sample with some context, not a solution.
* @author codeshane.com
* */
public class StackOverflow_Question_11513113 extends PreferenceActivity {
/*
*/
class MyPreferenceActivity extends PreferenceActivity {
//Preference keys that were either set in xml, or possibly in source via .setKey():
private final String pref_group_key = "some_prefs_key";
private final String list_pref_key = "some_list_key";
private final String edittext_pref_key = "some_edittext_key";
private PreferenceActivity mPreferenceActivity; /* the activity */
private SharedPreferences mSharedPreferences; /* auto-saving preferences */
private Editor mEdit;
private PreferenceScreen mPreferenceScreen; /* root of the preference hierarchy */
private PreferenceGroup mPreferenceGroup; /* optional grouping of preferences */
private ListPreference mListPreference; /* a pop-up selectable-items-list */
private EditTextPreference mEditTextPreference; /* a pop-up text entry box */
private int stored_new;
private int stored_ren;
/* ... */
public void setMonth() { /*SharedPreferences sp*/
/* ... */
//int stored_new = 0; //default value
//int stored_ren = 0; //default value
/* ... */
/* Should only call either apply() or commit(), not both; calling a .commit() after an .apply() can block the thread (always fun),
* not to mention they essentially do the same thing, just synchronously vs asynchronously.
* http://developer.android.com/reference/android/content/SharedPreferences.Editor.html#apply()
* */
// mEdit.apply(); //API level 9+, void, asynchronous.
// mEdit.commit(); //API level 1+, returns boolean, synchronous.
}
/* ... */
@Override
public void onCreate(Bundle savedInstanceState) {
/* Called once when the Activity is created. */
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.affirm_prefs);
/* ... */
}
@Override
protected void onResume() {
super.onResume();
/* Called when the Activity is created or comes to foreground. */
if (null==mSharedPreferences){init(this);}
mSharedPreferences.registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
/* manually load data from shared preferences that IS NOT REPRESENTED
* by a Preference already, or for which Persistent has been manually
* set to false. */
stored_new = mSharedPreferences.getInt("stored_new", 0); //If not found, assigns a default value of 0.
stored_ren = mSharedPreferences.getInt("stored_ren", 0); //If not found, assigns a default value of 0.
}
@Override
protected void onPause() { /* Called when the Activity goes to background. */
super.onPause();
mSharedPreferences.unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener);
/* manually save data to shared preferences that IS NOT REPRESENTED
* by a Preference already, or for which Persistent has been manually
* set to false. */
mEdit.putInt("stored_new", stored_new);
mEdit.putInt("stored_ren", stored_ren);
mEdit.commit();
}
private boolean init(PreferenceActivity activity){
mPreferenceActivity = activity; // or PreferenceActivity.this;
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
mPreferenceScreen = mPreferenceActivity.getPreferenceScreen();
mPreferenceGroup = (PreferenceGroup)mPreferenceScreen.findPreference(pref_group_key);
mListPreference = (ListPreference)mPreferenceScreen.findPreference(list_pref_key);
mEditTextPreference = (EditTextPreference)mPreferenceScreen.findPreference(edittext_pref_key);
return true;
}
/* When registered to a preference, this listener is notified of changes before saving.
* */
OnPreferenceChangeListener onPreferenceChangeListener = new OnPreferenceChangeListener(){
public boolean onPreferenceChange(Preference preference, Object newValue) {
boolean persistNewValue = true;
/* This occurs when a user has changed a preference, but before it is persisted */
/* this is a good place for your "setMonth" logic,
* at least in a PreferenceActivity*/
updateElement(preference, newValue);
changeMoreStuffBonusMethod(preference);
return persistNewValue;
}};
/* When registered to SharedPreferences, this listener is notified of all saves to SharedPreferences, even if the data is the same
* */
OnSharedPreferenceChangeListener onSharedPreferenceChangeListener = new OnSharedPreferenceChangeListener(){
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
}
};
private boolean updateElement(Preference prefUpdating, Object value){
if (null==prefUpdating) return false;
/* This function is for manually changing the value before it
* is saved by the PreferenceActivity. */
/* ... */
/* Can match exact instances, such as our mListPreference */
if (mListPreference.equals(prefUpdating)) {
/* set selected item by item's index id */
mListPreference.setValueIndex(0);
/* or set selected item by item's key*/
mListPreference.setValue("item_key");
}
/* Can also match by Class, such as any EditTextPreference */
if (prefUpdating instanceof EditTextPreference){
EditTextPreference etp = (EditTextPreference)prefUpdating;
String oldText = etp.getText();
etp.setText("Some new text in edit text box"); /* or */
etp.setText(String.valueOf(stored_new)); /* or */
etp.setText(oldText.trim()); /* remove leading/trailing whitespace */
etp.setText(dataModel.get(prefUpdating.getKey())); /* if you use a model.. */
}
/* ... */
}
private void changeMoreStuffBonusMethod(Preference prefUpdating){
/* Change the preference text */
prefUpdating.setTitle("Click Me!");
prefUpdating.setSummary("I am a cool preference widget!");
/* Change the pop-up list (not items) text */
if (prefUpdating instanceof ListPreference){
ListPreference lp = (ListPreference)prefUpdating;
lp.setDialogTitle("I am the pop-up.");
lp.setDialogMessage("Select something from my list.");
}
/* If persistent, PreferenceActivity should handle saving: */
Log.v(TAG,prefUpdating.getClass().getSimpleName()+".isPersistent="+String.valueOf(mListPreference.isPersistent()));
}
}
}