In my  Android application project, I need a solution how to keep a list of the object can be accessed from any activities. Initially, I download the list from the server, then I want the app just read the downloaded data without contacting the server again. We cannot put the list of the object directly into SharedPreferences. There are some solutions that I found on the forum. Let’s see.

  1. Using GSON

SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);

For saving the data

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

For retrieving the data

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

source

2. Using TinyDB

Basically, when we use TinyDB we need to utilize Gson. Before you implement the source code below, you must configure a few steps in the beginning.

This is how to implement TinyDB in saving and retrieving the list of the object.

TinyDB tinydb = new TinyDB(context);

to put

tinydb.putList("MyUsers", mUsersArray);

to get

tinydb.getList("MyUsers");

3. Using ObjectSerializer

You may also use the way below. First, store your List as a Set, and then convert it back to a List when you read from SharedPreferences.

Listtasks = new ArrayList<String>();
Set<String> tasksSet = new HashSet<String>(Listtasks);
PreferenceManager.getDefaultSharedPreferences(context)
    .edit()
    .putStringSet("tasks_set", tasksSet)
    .commit();

Then when you read it:

Set<String> tasksSet = PreferenceManager.getDefaultSharedPreferences(context)
    .getStringSet("tasks_set", new HashSet<String>());
List<String> tasksList = new ArrayList<String>(tasksSet);

source

 

Advertisements