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.
I had overcome this situation with a trick.
Now here is the trick while storing as key-value pair keep key "ArraylistName" + position of element
While retrieving:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With