2

I am using SharedPreferences to save and load my ArrayList like this: (save)

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

(Load) And this (they both work fine, both saves and loads correctly)

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

But the retrieved ArrayList has different element order than before. I know this because I put this ArrayList into a Dialog as a list (this list is refreshed every time I open it.), by Category.toArray(temArray), and the list is no longer alphabetical.

Before, this ArrayList alphabetically sorted String elements inside it. When I retrieve it back from the SharedPreferences, it is no longer alphabetically sorted.

Thank you for you help, in advance.

coolcool1994
  • 3,704
  • 4
  • 39
  • 43

2 Answers2

9

I had overcome this situation with a trick.

  1. In SharedPreferences first store the size of the ArrayList.
  2. In a for loop store the elements of the arraylist into the SharedPreferences File .

Now here is the trick while storing as key-value pair keep key "ArraylistName" + position of element

While retrieving:

  1. First retrieve the size of the arrayList
  2. for (i = 0 ; i < sizeOfList ; i++) { fetch element with key value "ArrayListName" + i }
Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
pvn
  • 2,016
  • 19
  • 33
1

In Java Set doesn't maintain the order of its elements. Unfortunately SharedPreferences.Editor doesn't provide a way to store a list so you should probably serialize the list into string and use putString().

See Store a List or Set in SharedPreferences.

Community
  • 1
  • 1
pingw33n
  • 12,292
  • 2
  • 37
  • 38