0

I want to store the last X values that a user input into a form. I have a list of 20 values and every time the user enters a new one, the oldest value is pushed out of the list and the newest value goes in. I want this list to persist between app launches, but sharedpreferences doesn't support an ordered set, so the results will end up jumbled every time. How can I store the list in an ordered form that I can then retrieve?

Set<String> previousValues = sharedPreferences.getStringSet(getString(R.string.LAST_VALUES), null);
Jon
  • 7,941
  • 9
  • 53
  • 105
  • 1
    You can convert them into one string, for example using json. Then parse it back from json into strings. You can also use SQLite if you have more data that you need to save between launches. – galvan Aug 04 '15 at 10:54
  • 2
    This is answered here: http://stackoverflow.com/questions/6598331/store-a-list-or-set-in-sharedpreferences – milez Aug 04 '15 at 10:56

2 Answers2

1

You can do this in several ways:

  • Create a SQLite database and store them in a table

  • Have a unique key in the sharedpreferences and use JSON to serialize them. You don't need to use the any external library, Android includes its own JSON classes,

  • Have multiple keys in the SharedPreference, one for each value, and an additional, numerical, for storing the index of the last one, something like:

 int index = ... // number of entries
 List<String> values = ... // the values you want to store
 SharedPreferences prefs = ...
 SharedPreferences.Editor editor = prefs.edit();
 editor.putInt("index", index);
 for (int i = 0 ; i < index ; i++) {
    editor.putString("value." + i, values.get(i)); // assuming your values are in a String collection called 'values'
 }

Of course, this snippet should give you the general idea, you would probably only add the last one every time and not all at once. When reading, you read first the index value, and then only index number of strings.

Sebastian
  • 1,076
  • 9
  • 24
-2

Using SharedPreferences it's easy, after API 11 the SharedPreferences Editor accept Sets as argument, so just create a Set with size of 20 and store it in shared preferences. When retrieved use it like any other java set to store only 20 values.

Set<String> lastValues = new HashSet<String>(20);

Get shared prefs

SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);

Set shared prefs

Editor editor = prefs.edit();
try {
    editor.putString(TASKS, ObjectSerializer.serialize(lastValues));
} catch (IOException e) {
    e.printStackTrace();
}
editor.commit();

Examples here and here

Community
  • 1
  • 1
Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
  • A `Set` isn't guaranteed to preserve order, and the question states that the list should be ordered. – tinsukE Aug 05 '20 at 12:31