9

I was wondering if it could be possible to save in the shared preferences an array of Strings, in a way that, every time we save a certain String, we store it in that array.

For example I have a list of locations with a certain ID that I want to mark as favorite. The ideal situation would be, having an array and saving a certain location ID (let's call it Location1) in that array, so next time I want to mark a new location as favorite (let's call it Location2), I retrieve that array (which so far contains Location1) and add the ID of this new location I want to add (Location2).

Android has methods to store primitive objects, but not for arrays. Any idea in order to do this, please?

Mat
  • 202,337
  • 40
  • 393
  • 406
noloman
  • 11,411
  • 20
  • 82
  • 129

3 Answers3

23

This is doable: I was just blogging about it:

SAVE YOUR ARRAY

//String array[]
//SharedPreferences prefs
Editor edit = prefs.edit();
edit.putInt("array_size", array.length);
for(int i=0;i<array.length; i++)
    edit.putString("array_" + i, array[i]);
edit.commit();

RETRIEVE YOUR ARRAY

int size = prefs.getInt("array_size", 0);
array = new String[size];
for(int i=0; i<size; i++)
    prefs.getString("array_" + i, null);

Just wrote that so there might be typos.

s.krueger
  • 1,043
  • 8
  • 13
Sherif elKhatib
  • 45,786
  • 16
  • 89
  • 106
  • 3
    Check answers of this post. http://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences – AndroidLearner May 30 '12 at 09:58
  • @noloman your welcome check the functions of the blog.. more generic – Sherif elKhatib May 30 '12 at 11:56
  • As @Shubhangi pointed out, you can save sets in sharedPreferences in API 11+, so it is much simpler. http://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences?lq=1 – Dick Lucas Nov 02 '14 at 18:11
15

You could make the array a JSON array and then store it like this:

SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0);
SharedPreferences.Editor editor = settings.edit();

JSONArray jArray = new JSONArray();
try {
    jArray.put(id);
} catch (JSONException e) {
    e.printStackTrace();
}

editor.putString("jArray", jArray.toString());
editor.commit();

You can then get the array like this:

SharedPreferences settings = getSharedPreferences("SETTINGS KEY", 0);
try {
    JSONArray jArray = new JSONArray(settings.getString("jArray", ""));
} catch (JSONException e) {
    e.printStackTrace();
}

Just an alternative solution that I have used in the past

beenjaminnn
  • 752
  • 1
  • 11
  • 23
1

Write methods to read and write a serialized array. This shouldn't be too difficult. Just flatten the array of strings into a single string that you store in the preferences. Another option would be to convert the array into an XML structure that you then store in the preferences, but that is probably overkill.

David Wasser
  • 93,459
  • 16
  • 209
  • 274