Saving Serializable Objects List into sharedPreferences
Easiest way out?
Convert to JSON
and save it as a String
.
Another good solution is to use GSON. Here's an example:
private static final String MAP = "map";
private static final Type MAP_TYPE = new TypeToken<Map<MyObjA, MyObjB>>() {}.getType();
private static SharedPreferences prefs = MyApplication.getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
private static Map<MyObjA, MyObjB> myMap;
public static void saveMap (Map<MyObjA, MyObjB> map) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString(MAP, new Gson().toJson(map));
editor.commit();
myMap = map;
}
public static Map<MyObjA, MyObjB> loadMap() {
if (myMap == null) {
myMap = new Gson().fromJson(prefs.getString(MAP, null), MAP_TYPE);
}
return myMap;
}
More information about gson at http://code.google.com/p/google-gson/
Pretty simple right? ;)
Take care
You can use the JSON format to serialize your ArrayList
and the objects it contains, and then store the String
result into the SharedPreferences
.
When you want to get the data back, retrieve the String and use a JSONArray
to retrieve each object and add it to a new ArrayList.
Otherwise you can simply use Object(Input/Output)Stream
classes and write it into a differente file using (for writing)
FileOutputStream fos = this.openFileOutput(fileName, MODE_PRIVATE);
final OutputStreamWriter osw = new OutputStreamWriter(fos);
JSONArray array = new JSONArray();
// Add your objects to the array
osw.write(array.toString());
osw.flush();
osw.close();