如果我理解正确,您似乎有一个 PreferenceActivity 使用 SharedPreferences 和一个 SQLiteDatabase 来持久化/保存相同的数据。虽然 PreferenceActivity 看起来像是为数据输入而设计的预构建 ListView,但它实际上更多:PreferenceActivity 会自动将 Preferences 保存并加载到 SharedPreferences,SharedPreferences 是分配给您的应用程序并由 Android 操作系统管理的特殊数据存储区。
尽管旨在存储首选项,但如果需要,您可以使用 SharedPreferences 来保存一些数据;可以通过首选项自动进行,也可以通过调用编辑器手动进行。您可以通过多种方式中断和/或修改此持久性,例如创建首选项子类来替换行为,使用 OnPreferenceChangeListener 来修改行为,或通过调用 setPersistent(boolean) 来切换持久性。
以这种方式使用 PreferenceActivity 的替代方法是使用 AdapterView 或 ListActivity 创建一个 Activity,并使用 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()));
}
}
}