0

I need some help in getting all sharedPreferences (keys & values) from my custom preference, but in order that they were originally inserted in the preference file. I currently have the below code but the problem is because getAll() returns a map the order changes.

public List<String> getPrefValues(String pref, Context context) {
    Map<String, ?> allEntries = context.getSharedPreferences(pref,
            Context.MODE_PRIVATE).getAll();
    List<String> command = new ArrayList<String>();
    for (Map.Entry<String, ?> entry : allEntries.entrySet()) {
        command.add(new StringBuilder(entry.getKey())
                .append(":")
                .append(entry.getValue()).toString());
    }
    if (command.isEmpty()) {
        return null;
    } else {
        return command;
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
wedgess
  • 68
  • 1
  • 8

3 Answers3

1

You can store your desired attributes in a LinkedHashSet, because there,

The iteration order is the order in which entries were inserted

Sets are stored in preferences with:

Set<String> mySet = new LinkedHashSet();
insertAttributes(mySet);

SharedPreferences myprefs = getPrefs();
myprefs.edit().putStringSet("myKey", mySet).commit();

This is also applicable to a map structure: simply create one set, that contains all keys, and one, that contains the values.

SME_Dev
  • 1,880
  • 13
  • 23
  • Looks like this doesn't work: https://stackoverflow.com/q/60785714/515455 – Daniel Ryan May 18 '22 at 02:45
  • @DanielRyan In the linked thread, the OP creates the set from an unspecified source collection, which also seems to be modifed on a public scope. So with the given information there it's more difficult to tell what's going on. – SME_Dev May 18 '22 at 12:36
0

There is NO facility in SharedPreferences for tracking insertion time. It would be better if you can figure another way (external to SP) to track this value.

Bottom line, there is no way within the current SP structure to understand 'insertion time'.

Booger
  • 18,579
  • 7
  • 55
  • 72
0

You can use the prefix as numbers for the keys when you put in the order you want to get them out.

For example: 00data, 01foo, 02cree.

Then 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);
sjain
  • 23,126
  • 28
  • 107
  • 185