Shared Preferences: Saving ArrayLists (and more!) with Json and Gson | Java

Evan Chee
3 min readJan 12, 2018

Many developers often need a way to save user info to the phone whether be it names, lists of to do-tasks or records for each different activity, saving small pieces of data is a necessity. Often new coders look up extremely long, tedious, and complicated ways just to save one ArrayList. However, learning to use Shared Preferences can b as ez as learning “Hello World!”. Don’t we all remember our first:

System.out.println("Hello World!"); //if u dun know da way then u fake boi >:( 

Can b as ez as learning “Hello World!”

So to start off, you can think of Gson as a transformer between objects like strings and ints (which includes arrayLists of these types!) and Json as a transformer between Json and Shared Preferences. So to save things, all you need to do is:

public void saveTasksToSharedPrefs(Context context) {
SharedPreferences appSharedPrefs = PreferenceManager .getDefaultSharedPreferences(context.getApplicationContext());
SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(tasks); //tasks is an ArrayList instance variable
prefsEditor.putString("currentTasks", json);
prefsEditor.commit();
}

So I know this looks like a lot but it’s not too bad once you get. Let’s break it down line by line. The first line creates a Shared Preferences object, which is self explanatory given that that’s what you’re saving to. But this specific object is actually a manager or control system for the device’s Shared Preferences, which is why it gets the application context so it can use the proper preference. The second line is similar in that it just makes a Shared Preferences editor and the method allows it to edit the Shared Preferences.

The next two lines are devoted to making Gson and Json objects. However, when creating the Json, the tasks variable is stored in the Gson, then translated to a Json object.

If you use the wrong name then you get a null pointer exception and your app crashes! Fun!

The fifth line is giving a name to the Json object that is about to be saved so the Json can be accessed later. Make sure you name the Json reasonably and something that can be remembered because you need to it to retrieve it. If you use the wrong name then you get a null pointer exception and your app crashes! Fun! And the last line simply saves it.

Now let’s explore how to retrieve what we just saved:

public List<Task> getTasksFromSharedPrefs(Context context) {
SharedPreferences appSharedPrefs = PreferenceManager .getDefaultSharedPreferemces(context.getApplicationContext());
Gson gson = new Gson();
String json = appSharedPrefs.getString("currentTasks", "");
tasks = gson.fromJson(json, new TypeToken<ArrayList<Task>>(){}.getType());
return tasks;
}

Now this one should look a bit easier to deal with. Just like before we need to create a Shared Preferences manager to retrieve our data and a new Gson object. This time the Json object is retrieving the array list. Notice how we used the exact same name that we named it earlier to retrieve the array list. If the same name isn’t used, then you’ll just get null.

Notice how we used the exact same name that we named it earlier to retrieve the array list.

Next we got a somewhat new line than the first method. In short we create a new array list just like the one we want to set to the instance variable tasks. Like in the previous method we need to translate the Json file. The new TypeToken and ArrayList stuff is just to allow us to create a literal array list that we can store our new array list in.

And it’s as ez pz as 123! If you wanted below are some lines for saving and retrieving the info.

tasks = getTasksFromSharedPrefs(this);
if (tasks == null){
tasks = new ArrayList<>();
tasks.add(new Task("Your first task!", "Check this task to complete your first task!", "01/01/18"));
} //I put the above in the onResume method. Check Sean McClane's article for info on the Android life cycle!

Retrieving:

saveTasksToSharedPrefs(this); //too ez for rtz ikr
//this goes in the onPause

Oh and I forgot to say but don’t forget to import these two things at the top of your program. You should have auto import unambiguous stuff on the fly option on but in case you don’t:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

Hope you enjoyed this tutorial and found it helpful!

--

--