在SharedPreferences中存储<String> ArrayList会混淆元素顺序

coo*_*994 2 android

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

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

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

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

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

之前,这个ArrayList按字母顺序排序其中的String元素.当我从SharedPreferences中检索回来时,它不再按字母顺序排序.

提前谢谢你的帮助.

pvn*_*pvn 9

我用一招来克服了这种情况.

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

现在这里是存储为键值对的技巧,保持键"ArraylistName"+元素的位置

检索时:

  1. 首先检索arrayList的大小
  2. for(i = 0; i <sizeOfList; i ++){fetch元素的键值为"ArrayListName"+ i}