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: I don't want to use Database
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: I don't want to use Database
This is the shared preferences code i use successfully, Refer this link:
HAPPY CODING!
Regardless of the API level, Check String arrays and Object arrays in SharedPreferences
SAVE ARRAY
LOAD ARRAY
I loaded an array of waist sizes (already created in my array.xml) into my preferences.xml file with the code below. @array/pant_inch_size is the id of the entire array.
This populated the menu with choices from the array. I set the default size as 34, so when the menu pops up, they see size 34 is pre-selected.
The Simple way is, to convert it to JSON String as below example:
Then store the string in the shared preferences. Once you need it just get string from shared preferences and convert back to JSONArray or JSONObject(as per your requirement.)
So from the android developer site on Data Storage:
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:
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
Shared preferences introduced a
getStringSet
andputStringSet
methods in API Level 11, but that's not compatible with older versions of Android (which are still popular), and also is limited to sets of strings.Android does not provide better methods, and looping over maps and arrays for saving and loading them is not very easy and clean, specially for arrays. But a better implementation isn't that hard:
Now you can save any collection in shared preferences with this five methods. Working with
JSONObject
andJSONArray
is very easy. You can useJSONArray (Collection copyFrom)
public constructor to make aJSONArray
out of any Java collection and useJSONArray
'sget
methods to access the elements.There is no size limit for shared preferences (besides device's storage limits), so these methods can work for most of usual cases where you want a quick and easy storage for some collection in your app. But JSON parsing happens here, and preferences in Android are stored as XMLs internally, so I recommend using other persistent data store mechanisms when you're dealing with megabytes of data.