2013-05-29 19 views
3

我在存儲字符串集偏好時遇到了問題。我有這些實用的方法來存儲:Android:字符串集偏好不是持久的

public static void putStringSet(SharedPreferences pref, Editor e, String key, Set<String> set) 
{ 
    if (Utils.isApiLevelGreaterThanGingerbread()) 
    { 
     // e.remove(key); // I tried to remove it here 
     e.putStringSet(key, set); 
    } 
    else 
    { 
     // removes old occurences of key 
     for (String k : pref.getAll().keySet()) 
     { 
      if (k.startsWith(key)) 
      { 
       e.remove(k); 
      } 
     } 

     int i = 0; 
     for (String value : set) 
     { 
      e.putString(key + i++, value); 
     } 
    } 
} 

public static Set<String> getStringSet(SharedPreferences pref, String key, Set<String> defaultValue) 
{ 
    if (Utils.isApiLevelGreaterThanGingerbread()) 
    { 
     return pref.getStringSet(key, defaultValue); 
    } 
    else 
    { 
     Set<String> set = new HashSet<String>(); 

     int i = 0; 

     Set<String> keySet = pref.getAll().keySet(); 
     while (keySet.contains(key + i)) 
     { 
      set.add(pref.getString(key + i, "")); 
      i++; 
     } 

     if (set.isEmpty()) 
     { 
      return defaultValue; 
     } 
     else 
     { 
      return set; 
     } 
    } 
} 

我使用這些方法向後兼容GB。但我有一個問題,即使用putStringSet方法對於API>薑餅不是持久的。它在應用程序運行時保持不變。但重啓後消失。我將介紹的步驟:

  1. 乾淨安裝應用程序的 - 沒有與主要X沒有偏好
  2. 我存儲的字符串集合A與關鍵X - 偏好包含
  3. 我存儲串集B與鍵X - 優選含有B
  4. 關閉應用
  5. 應用的重啓 - 偏好包含
  6. 我串集合C存儲與密鑰X - 優選含有C
  7. 氯OSE應用
  8. 應用程序的重新啓動 - 偏好包含

所以只有第一個值是持久的,我不能覆蓋它。

其他說明:

  1. 這種方法只是取代putStringSet和getStringSet。所以我使用commit()...但在其他地方(見下面的例子)。
  2. 我試圖用apply()取代commit() - 沒有成功
  3. 當我在較新的API中使用舊代碼的代碼(我在兩個方法中評論了前四行)時,它的工作原理完美無缺,但效率不高使用

例子:

Editor e = mPref.edit(); 
PreferencesUtils.putStringSet(mPref, e, GlobalPreferences.INCLUDED_DIRECTORIES, dirs); 
e.commit(); 

Thnak你非常的幫助。

+0

您如何初始化dirs? –

+0

[嘗試存儲使用SharedPreferences的字符串集時出現錯誤行爲]的可能重複(http://stackoverflow.com/questions/14034803/misbehavior-when-trying-to-store-a-string-set-using-sharedpreferences) –

回答

1

我的條件與您的條件非常相似,唯一的區別是重新啓動應用程序時,首選項包含A,B,C,但重新安裝或重新啓動手機時,B & C已不存在。

我也試着用apply()替換commit(),因爲這篇文章提示SharedPreferences not persistent,但是還是不行。

我解決了刪除&這個問題提交喜好更換前:

editor.remove("StringSetKey"); 
editor.commit(); 

editor.putStringSet("StringSetKey", newSet); 
editor.commit(); 

PS:你可以在CMD行中鍵入adb pull /data/data/<packagename>/shared_prefs/xxxx.xml,看是否提交()真的有用

PPS:我認爲這是一個錯誤與putStringSet ....

希望這會幫助你;)

+0

我給你一個-1,因爲你所要做的只是閱讀[javadoc for getStringSet()](http://developer.android.com/reference/android/content/SharedPreferences.html#getStringSet%28java.lang.String ,%20java.util.Set%3Cjava.lang.String%3E%29):_注意你不能修改這個調用返回的set實例。如果存儲數據的一致性不能得到保證,也不能保證你可以修改實例。當你遇到問題時,解決方案不是黑客,而是理解發生的事情。 _爲什麼你必須刪除設置並重新添加?這是否真的對你有意義?_ –

+0

@Mr_and_Mrs_D thx提及 – zhangxaochen

+0

編輯你的答案是正確的,將撤銷我的投票 –