Sometime we need to save ArrayList of Objects into Shared preferences so that we can use that data in multiple Activities when required. We can do that easily as below:
Suppose we have model Users as below:
public class Users
{
private int id;
private String name;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
And we want to save the ArrayList of users in SharedPreferences.
To save ArrayList of Users in SharedPreferences use the following code:
// Create List of users that you want to save
ArrayList userList = new ArrayList();
userList.add(new Users());
userList.add(new Users());
SharedPreferences prefs = getSharedPreferences("User", Context.MODE_PRIVATE);
//save the user list to preference
Editor editor = prefs.edit();
try {
editor.putString("UserList", ObjectSerializer.serialize(userList));
} catch (IOException e) {
e.printStackTrace();
}
editor.commit();
To retrieve the list of users from preferences use the following code:
ArrayList userList = new ArrayList();
// Load user List from preferences
SharedPreferences prefs = getSharedPreferences("User", Context.MODE_PRIVATE);
try {
userList = (ArrayList) ObjectSerializer.deserialize(prefs.getString("UserList", ObjectSerializer.serialize(new ArrayList())));
} catch (IOException e) {
e.printStackTrace();
}
You can get ObjectSerializer class from the following link
github.com
Hope this will help you :)
0 Comment(s)