save – android SharedPreferences putStringSet order/sort-ThrowExceptions

Exception or error:

I try to save/restore a set of string and all is working except one thing.
When i create my strings i put :

Set<String> set = new HashSet<String>();
for(int i=0; i<toggles.size();i++){
   set.add(toggles.get(i).serialise());                 
}

Order is for example “blutooth” “application” “data”.
When i get back set :

Set<String> set = prefs.getStringSet(key, new HashSet<String>());
for (String toggle : set){
    Toggle t = new Toggle();
    t.deserialize(toggle);
    toggles.add(t); 
}

I get “application” “bluetooth” “data” they are sort by name and i don’t want this.
I want to get same order i have save.
Anyone can help me ?

How to solve:

This is not possible. Sets are unordered collections.

###

You can prefix your strings by numbers, for instance 00application, 01bluetooth, 02data, in the order you want to get them out. Put the Set<String> returned from getStringSet in an Array<Set> and sort it.

Set<String> set = prefs.getStringSet(key, new HashSet<String>());
Array<String> a = set.toArray();
java.util.Arrays.sort(a);

###

You can save a list of string as a single string with a delimiter.
For example this is your array:

["Italy", "France", "Spain", "Japan", "United States"]

You can save it as:

"Italy;France;Spain;Japan;United States"

In code:

SharedPreferences sharedPref = mContext.getSharedPreferences(PREF_KEY, Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();

// countries is your List
String countriesString = TextUtils.join(";", countries);
editor.putString("countries", countriesString);
editor.apply();

To retrieve your data:

final String countriesString = sharedPref.getString("countries", "");
List<String> countries = new ArrayList<>();
if (!countriesString.isEmpty()){
    countries = new ArrayList<>(Arrays.asList(countriesString.split(";")));
}

Leave a Reply

Your email address will not be published. Required fields are marked *