2

I have an ArrayList that can contain 1 to 15 strings. Those strings need to be saved in my shared preferences, now I know how to iterate trough the array to get the strings. What I don't know, is there a clean way to dynamically add the strings to my shared preferences file? I could do this on a sluggish way by creating 15 strings and using an if statement to fill the shared preference, but I would like to know if there is a better way.

Thank you.

Raymond P
  • 752
  • 2
  • 15
  • 27
  • Have You tried SharedPreferences.Editor.putStringSet() ? – sandrstar Mar 28 '13 at 09:18
  • You can use a Database instead of Shared Preferences: i think is better for CRUD operation with your data. – JJ86 Mar 28 '13 at 09:19
  • see this excellent post for [Save ArrayList to SharedPreferences](http://stackoverflow.com/questions/7057845/save-arraylist-to-sharedpreferences) instead of creating 15 keys in sharedpreferences and you can also do same by converting ArrayList to JsonArray – ρяσѕρєя K Mar 28 '13 at 09:24
  • API 11 is not gonna work for this particular app. – Raymond P Mar 29 '13 at 13:46

3 Answers3

5

You can use the putStringSet method available in SharedPreferences.Editor to store string arrays. For example:

String[] array = new String[]{"this", "is", "a", "string", "array"};
SharedPreferences.Editor edit = sharedPrefs.edit();
edit.putStringSet("myKey", new HashSet<String>(Arrays.asList(array)));
edit.commit();

Or if your API is below 11 then you may convert your string array into a single string and save it just like an ordinary string. For example:

edit.putString("myKey", TextUtils.join(",", array));

and later use the following to rebuild your array from string:

array = TextUtils.split(sharedPrefs.getString("myKey", null), ",");
waqaslam
  • 67,549
  • 16
  • 165
  • 178
5

If its about naming, you can use something like this:

public static final String mPrefix = "mArray";
SharedPreferences prefs;
prefs  = this.getSharedPreferences("PREF", 0);
prefsEditor = appSharedPrefs.edit();

//mAL is your ArrayList

for(int i=0; i<mAl.size(); i++){

prefsEditor.putString(mPrefix + "-" + i, mAl.get(i));
}
prefsEditor.commit();
Archie.bpgc
  • 23,812
  • 38
  • 150
  • 226
1

Mainly to edit the shared prefernces data you need to take the Editor Object from it so you could edit it freely so to put data in it:

SharedPrefernces preferences = mContext.getSharedPreferences(MODE_PRIVATE);
Editor prefEditor = preferences.edit();
prefEditor.putString("this is a key object","this is value of the key");

You can also put inside different kinds of object for example : boolean , int , float , double and etc.... Just look up the editor class in android developers website...

In order to read the data from the sharedPrefrences it is even more simplier

SharedPrefrences pref = mContext.getSharedPreferences(MODE_PRIVATE);
pref.getString("the key of the value");
Ido
  • 9
  • 5