Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 502
Paul Blundell Avatar asked Feb 20 '13 13:02

Paul Blundell


People also ask

Can we store array in SharedPreferences?

You can save String and custom array list using Gson library. =>First you need to create function to save array list to SharedPreferences. public void saveListInLocal(ArrayList<String> list, String key) { SharedPreferences prefs = getSharedPreferences("AppName", Context. MODE_PRIVATE); SharedPreferences.

Can we store HashMap in SharedPreferences?

Android App Development for Beginners This example demonstrates about How can I save a HashMap to Shared Preferences in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.

Is SharedPreferences Singleton?

I've noticed that a lot of projects have their SharedPreferences code scattered all over the project. The reason for this mostly is that fetching SharedPreference and reading/writing preferences as and when needed is the easiest thing to do when writing an app.


1 Answers

Yes, you can save your composite object in shared preferences. Let's 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 retrieve 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 an ArrayList of any type object e.g. Student, then use:

Type type = new TypeToken<List<Student>>(){}.getType(); List<Student> students = gson.fromJson(json, type); 
like image 131
Mohammad Imran Avatar answered Oct 13 '22 04:10

Mohammad Imran