0

我目前正在使用 SharedPreferences 开发一个应用程序,并且我正在尝试动态更改出现在 Prefs 活动屏幕上的值。在屏幕上,我有一个偏好列表视图,其中包含一年中的月份和两个编辑框,用于存储与所选月份相关的信息。选择一个月后,我希望发生一些事情:

  1. 在选定月份的数据库中插入一行(如果之前没有选择过)——这我可以开始工作了
  2. 将 sharedpreference 编辑框的值更改为存储在数据库行中的值——这是我遇到问题的地方
  3. 更新编辑框时,它们应该根据所选月份更新数据库中的相应行——没有问题。

所以,基本上,我的问题在于项目#2。我有一个功能可以检查何时从列表中选择了新月份:

public void setMonth(SharedPreferences sp) {
            ContentValues cv = new ContentValues();
    cv.clear();

    int sel_month = Integer.valueOf(sp.getString("pActivityMonth", String.valueOf(this.month))); //listvew works with strings, convert to int
    int stored_new = 0; //default value
    int stored_ren = 0; //default value

    Log.d(TAG, String.valueOf(sel_month));

    String[] col = { Database.C_MONTH, Database.C_QNEW, Database.C_QRENEW };
    String[] arg = { String.valueOf(sel_month) };

    Cursor c = db.query(Database.RR_TABLE, col, Database.C_MONTH + "=?", arg, null, null, null);

    if (c.getCount()<1) { //New month, insert row
        cv.put(Database.C_MONTH, sel_month);
        db.insertWithOnConflict(Database.RR_TABLE, null, cv, SQLiteDatabase.CONFLICT_IGNORE);
    } else { //row exists, get stored values
        Log.d(TAG, "cursor count: " + String.valueOf(c.getCount()));
        c.moveToFirst();
        stored_new = c.getInt(c.getColumnIndex(Database.C_QNEW));
        stored_ren = c.getInt(c.getColumnIndex(Database.C_QRENEW));
        Log.d(TAG, "stored_new: " + String.valueOf(stored_new));
    }

            //Change edittext preferences to stored values
    editor.putString("pNewQuota", String.valueOf(stored_new));
    editor.putString("pRenewQuota", String.valueOf(stored_ren));
    editor.apply();
    editor.commit();



}

因此,我选择了一个新月份(七月),单击其中一个 edittext 选项来更新信息(假设我输入了 20),然后选择一个不同的月份(八月),默认值为 0。如果我然后单击再次在 edittext 上,对话框继续显示 20 而不是 0。如果我将此 0 更改为其他值,它将存储在数据库的正确行中,但随后此值在更改为另一个月后继续存在(例如,回到七月)。我的 Logcat 显示该函数正在获取正确的值,并且 putString 正在运行。PreferenceScreen 不能自行刷新吗?谢谢你的帮助。

4

1 回答 1

1

如果我理解正确,您似乎有一个 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()));
            }
        }
    }
于 2012-10-17T16:46:32.603 回答