【问题标题】:Storing <String> ArrayList in SharedPreferences messes up the element order在 SharedPreferences 中存储 <String> ArrayList 会打乱元素顺序
【发布时间】:2013-01-23 12:13:34
【问题描述】:

我正在使用 SharedPreferences 来保存和加载我的 ArrayList,如下所示: (保存)

        SharedPreferences loadGlobalVariables = getSharedPreferences(APP_NAME, 0);
        Categories = new ArrayList<String>(loadGlobalVariables.getStringSet("Categories", new HashSet<String>()));

(加载) 和这个 (它们都工作正常,保存和加载都正确)

 SharedPreferences saveGlobalVariables = getSharedPreferences(APP_NAME, 0);
    SharedPreferences.Editor editor = saveGlobalVariables.edit();
    editor.putStringSet("Categories", new HashSet<String>(Categories));
    editor.commit();

但检索到的 ArrayList 的元素顺序与以前不同。我知道这一点是因为我将这个 ArrayList 作为一个列表放入一个 Dialog(每次打开它都会刷新这个列表。),按 Category.toArray(temArray),并且该列表不再按字母顺序排列。

之前,这个ArrayList里面的String元素是按字母顺序排序的。当我从 SharedPreferences 中检索它时,它不再按字母顺序排序。

提前感谢您的帮助。

【问题讨论】:

  • 哈希和集合是无序的。

标签: android


【解决方案1】:

我用一个技巧克服了这种情况。

  1. 首先在 SharedPreferences 中存储 ArrayList 的大小。
  2. 在 for 循环中,将数组列表的元素存储到 SharedPreferences 文件中。

现在这里是作为键值对保存键“ArraylistName”+元素位置的技巧

检索时:

  1. 先检索arrayList的大小
  2. for (i = 0 ; i

【讨论】:

  • 这是个好主意!我也在想类似的事情!如果可行,我会尝试并标记为答案
  • 完美。谢谢! (我也点赞了:))
【解决方案2】:

在 Java 中 Set 不维护其元素的顺序。不幸的是,SharedPreferences.Editor 没有提供存储列表的方法,因此您可能应该将列表序列化为字符串并使用putString()

Store a List or Set in SharedPreferences

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 2018-06-13
    • 2016-01-07
    • 2015-02-22
    相关资源
    最近更新 更多