Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...