Android Arraylist of Custom Objects - Save to Sharedpreferences - Serializable

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

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

Save ArrayList to SharedPreferences

After API 11 the SharedPreferences Editor accepts Sets. You could convert your List into a HashSet or something similar and store it like that. When you read it back, convert it into an ArrayList, sort it if needed and you're good to go.

//Retrieve the values
Set<String> set = myScores.getStringSet("key", null);

//Set the values
Set<String> set = new HashSet<String>();
set.addAll(listOfExistingScores);
scoreEditor.putStringSet("key", set);
scoreEditor.commit();

You can also serialize your ArrayList and then save/read it to/from SharedPreferences. Below is the solution:

EDIT:

Ok, below is the solution to save ArrayList as a serialized object to SharedPreferences and then read it from SharedPreferences.

Because API supports only storing and retrieving of strings to/from SharedPreferences (after API 11, it's simpler), we have to serialize and de-serialize the ArrayList object which has the list of tasks into a string.

In the addTask() method of the TaskManagerApplication class, we have to get the instance of the shared preference and then store the serialized ArrayList using the putString() method:

public void addTask(Task t) {
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}
currentTasks.add(t);

// save the task list to preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);
Editor editor = prefs.edit();
try {
editor.putString(TASKS, ObjectSerializer.serialize(currentTasks));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
}

Similarly we have to retrieve the list of tasks from the preference in the onCreate() method:

public void onCreate() {
super.onCreate();
if (null == currentTasks) {
currentTasks = new ArrayList<task>();
}

// load tasks from preference
SharedPreferences prefs = getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE);

try {
currentTasks = (ArrayList<task>) ObjectSerializer.deserialize(prefs.getString(TASKS, ObjectSerializer.serialize(new ArrayList<task>())));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

You can get the ObjectSerializer class from the Apache Pig project ObjectSerializer.java

How to save List Object to SharedPreferences?

It only possible to use primitive types because preference keep in memory. But what you can use is serialize your types with Gson into json and put string into preferences:

private static SharedPreferences sharedPreferences = context.getSharedPreferences(STORE_FILE_NAME, Context.MODE_PRIVATE);

private static SharedPreferences.Editor editor = sharedPreferences.edit();

public <T> void setList(String key, List<T> list) {
Gson gson = new Gson();
String json = gson.toJson(list);

set(key, json);
}

public static void set(String key, String value) {
editor.putString(key, value);
editor.commit();
}

Extra Shot from below comment by @StevenTB

To Retrive

 public List<YourModel> getList(){
List<YourModel> arrayItems;
String serializedObject = sharedPreferences.getString(KEY_PREFS, null);
if (serializedObject != null) {
Gson gson = new Gson();
Type type = new TypeToken<List<YourModel>>(){}.getType();
arrayItems = gson.fromJson(serializedObject, type);
}
}

ArrayList of custom objects not saving to SharedPreferences with GSON

Try to remove AtomicReference and add item to list directly as in

ArrayList<ItmModel> arrayList = new ArrayList<>();
ItmModel itmModel = new ItmModel(item.getText().toString(), attr.getText().toString(),pric.getText().toString(), sise.getText().toString(), image, company);
arrayList.add(itmModel);

Gson gson = new Gson();
Type type = new TypeToken<ArrayList<ItmModel>>() {}.getType();
String list = gson.toJson(arrayList, type);
prefsEditor.putString("Cart", list);
prefsEditor.apply();

Why are you even extending ArrayList in POJO, remove and modify part of your POJO to below

public class ItmModel implements Parcelable, Serializable {
@SuppressWarnings("unused")
public static final Parcelable.Creator<ItmModel> CREATOR = new Parcelable.Creator<ItmModel>() {
@Override
public ItmModel createFromParcel(Parcel in) {
return new ItmModel(in);
}

@Override
public ItmModel[] newArray(int size) {
return new ItmModel[size];
}
};
@Expose
private String name;
@Expose
private String attr;
@Expose
private String size;
@Expose
private String pric;
@Expose
private String imag;
@Expose
private String comp;
//rest of code as it is
}

Save custom object array to Shared Preferences

You can use gson to serialize class objects and store them into SharedPreferences. You can downlaod this jar from here https://code.google.com/p/google-gson/downloads/list

SharedPreferences  mPrefs = getPreferences(Context.MODE_PRIVATE);

To Save:

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(MyObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

To Retreive:

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Android. Easy way to save small arrayList of custom objects

There is a library for this kind of stuff with easy solution

compile 'com.google.code.gson:gson:2.4'

So, by importing this you can directly save/retrive you arrylist like this ::

SAVE ::

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
Type listOfBecons = new TypeToken<List<BeaconDevice>>() {}.getType();

String strBecons = new Gson().toJson(SavedBeacons, listOfBecons);
preferences.edit().putString("BECON_LIST", strBecons).apply();

RETRIEVE::

ArrayList<BeaconDevice> mSavedBeaconList = new Gson().fromJson(preferences.getString("BECON_LIST", ""), listOfBecons);


Related Topics



Leave a reply



Submit