Paul Blundell Paul Blundell - 1 month ago 22
Android Question

Android ArrayList of custom objects - Save to SharedPreferences - Serializable?

I have an ArrayList of an object. The object contains the types 'Bitmap' and 'String' and then just getters and setters for both. First of all is Bitmap serializable?

How would I go about serializing this to store it in SharedPreferences? I have seen many people ask a similar question but none seem to give a good answer. I would prefer some code examples if at all possible.

If bitmap is not serializable then how do I go about storing this ArrayList?

many thanks.

Answer

Yes,you can save your composite object in shared preferences.Let say:

 Student mStudentObject=new Student();
 SharedPreferences appSharedPrefs = PreferenceManager
  .getDefaultSharedPreferences(this.getApplicationContext());
  Editor prefsEditor = appSharedPrefs.edit();
  Gson gson = new Gson();
  String json = gson.toJson(mStudentObject);
  prefsEditor.putString("MyObject", json);
  prefsEditor.commit(); 

and now you can retreive your object as:

     SharedPreferences appSharedPrefs = PreferenceManager
      .getDefaultSharedPreferences(this.getApplicationContext());
      Gson gson = new Gson();
 String json = appSharedPrefs.getString("MyObject", "");
  Student mStudentObject = gson.fromJson(json, Student.class);

for more information,click here.

If you want to get back Array List of type any any object e.g. student, then use:

Type type = new TypeToken<List<Student>>(){}.getType();
List<Student> students= gson.fromJson(json, type);