Android ArrayList of custom objects - Save to SharedPreferences - Serializable?
The answer above works, but not for list:
For saving list of objects do like this:
List<Cars> cars= new ArrayList<Cars>();
cars.add(a);
cars.add(b);
cars.add(c);
cars.add(d);
gson = new Gson();
String jsonCars = gson.toJson(cars);
Log.d("TAG","jsonCars = " + jsonCars);
Read the json object:
Type type = new TypeToken<List<Cars>>(){}.getType();
List<Cars> carsList = gson.fromJson(jsonCars, type);
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);
For me it worked like this :
Put values in SharedPreferances :
String key = "Key";
ArrayList<ModelClass> ModelArrayList=new ArrayList();
SharedPreferences shref;
SharedPreferences.Editor editor;
shref = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Gson gson = new Gson();
String json = gson.toJson(ModelArrayList);
editor = shref.edit();
editor.remove(key).commit();
editor.putString(key, json);
editor.commit();
To get values from SharedPreferances :
Gson gson = new Gson();
String response=shref.getString(key , "");
ArrayList<ModelClass> lstArrayList = gson.fromJson(response,
new TypeToken<List<ModelClass>>(){}.getType());