Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing <String> ArrayList in SharedPreferences messes up the element order

Tags:

android

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.

like image 828
coolcool1994 Avatar asked Feb 24 '26 01:02

coolcool1994


2 Answers

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 }
like image 160
pvn Avatar answered Feb 25 '26 14:02

pvn


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.

like image 24
pingw33n Avatar answered Feb 25 '26 15:02

pingw33n



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!