Can't Control Order of String Set in Shared Preferences
It is unfortunate, but you have simply found a limitation of SharedPreferences
.
While you are using an orderd hash, it does not load them ordered when you call getStringSet
.
The quickest simplest way I have found of doing this is to convert your array into text, ordered, and then save that into the SharedPreferences. Android comes with an object JSONArray
that can do this.
http://developer.android.com/reference/org/json/JSONArray.html
Here is some pseudo code that will do what you want:
public void saveOrderedCollection(Collection collection, String key){
JSONArray jsonArray = new JSONArray(collection);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, jsonArray.toString());
editor.commit();
}
public Collection loadOrderedCollection(String key){
ArrayList arrayList = new ArrayList;
SharedPreferences.Editor editor = sharedPreferences.edit();
JSONArray jsonArray = new JSONArray(editor.getString(key, "[]"));
for (int i = 0; i < jsonArray.length(); i++) {
arrayList.put(jsonArray.get(i));
}
return arrayList;
}
Here are some other posts that I used to make this:
Is it possible to add an array or object to SharedPreferences on Android
In shared preferences how to store string array in android application