2014-09-23 55 views
0

我需要一些幫助才能從我的自定義首選項中獲取所有sharedPreferences(鍵值&值),但這是爲了使它們最初插入到首選項文件中。我目前有下面的代碼但問題是因爲getAll()返回一個映射順序的變化。需要獲取所有sharedPreferences但按正確的插入順序

public List<String> getPrefValues(String pref, Context context) { 
    Map<String, ?> allEntries = context.getSharedPreferences(pref, 
      Context.MODE_PRIVATE).getAll(); 
    List<String> command = new ArrayList<String>(); 
    for (Map.Entry<String, ?> entry : allEntries.entrySet()) { 
     command.add(new StringBuilder(entry.getKey()) 
       .append(":") 
       .append(entry.getValue()).toString()); 
    } 
    if (command.isEmpty()) { 
     return null; 
    } else { 
     return command; 
    } 
} 

回答

0

您可以將您想要的屬性在LinkedHashSet,因爲在那裏,

迭代順序就是插入

集存儲在偏好的條目順序:

Set<String> mySet = new LinkedHashSet(); 
insertAttributes(mySet); 

SharedPreferences myprefs = getPrefs(); 
myprefs.edit().putStringSet("myKey", mySet).commit(); 

這也適用於地圖結構:只需創建一個包含所有鍵的集合和一個包含值。

0

SharedPreferences中沒有用於跟蹤插入時間的工具。如果你能以另一種方式(SP外部)跟蹤這個值,那將會更好。

底線,當前SP結構中沒有辦法理解'插入時間'。

0

當您按照您希望將它們取出的順序放置時,您可以使用前綴作爲鍵的數字。

例如:00data,01foo,02cree

然後把返回Set<String>getStringSetArray<Set>和排序它 -

Set<String> set = prefs.getStringSet(key, new HashSet<String>()); 
Array<String> a = set.toArray(); 
java.util.Arrays.sort(a);