I have an ArrayList
of objects that have a name and an icon pointer and I want to save it in SharedPreferences
. How can I do?
NOTE:
So from the android developer site on Data Storage:
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
So I think it is okay since it is simply just key-value pairs which are persisted.
To the original poster, this is not that hard. You simply just iterate through your array list and add the items. In this example I use a map for simplicity but you can use an array list and change it appropriately:
// my list of names, icon locations
Map nameIcons = new HashMap();
nameIcons.put("Noel", "/location/to/noel/icon.png");
nameIcons.put("Bob", "another/location/to/bob/icon.png");
nameIcons.put("another name", "last/location/icon.png");
SharedPreferences keyValues = getContext().getSharedPreferences("name_icons_list", Context.MODE_PRIVATE);
SharedPreferences.Editor keyValuesEditor = keyValues.edit();
for (String s : nameIcons.keySet()) {
// use the name as the key, and the icon as the value
keyValuesEditor.putString(s, nameIcons.get(s));
}
keyValuesEditor.commit()
You would do something similar to read the key-value pairs again. Let me know if this works.
Update: If you're using API level 11 or later, there is a method to write out a String Set