Android Essentials → Android SharedPreferences – Camposha

Android Essentials

Android Essentials

Android SharedPreferences

Android SharedPreferences Tutorial and Examples

In this tutorial we want to look at SharedPreferences, what it is, why it’s important and several examples.

Here are some SharedPreferences examples.

2. How to save and retrieve JSON data in SharedPreference

Let’s start by creating our main application.

This class is deriving from the Application class. All it will do for us is hold and give us the to the application Context.

Then having created our application class we can now come and save and load our json data.

The first method is the save() method. It will receive two strings and an Object.

We are using the Google Gson library. It’s a third party library so has to be added as a dependency in your app level build.gradle file.

So you go to your build.gradle file(located in the app folder) and add the following line under the dependencies closure:

Maybe you can check for the later versions.

Then once we’ve synced the project we start by instantiating our Gson;

Then get our SharedPreferences:

Then obtain a SharedPreference.Editor object by invoking the edit() method of our SharedPreferences class.

Then convert our object to JSON using the toJson() method of Gson class. Then put that JSON data alongside the key to our SharedPreference.Editor instance, and invoke the apply() method:

That’s how we save the JSON data to SharedPreferences.

What about loading that data? Well we can also easily load that data. Again you instantiate the Gson and initialize our SharedPreferences.

We then get our data as a JSON string by invoking the getString() method of the SharedPreferences class, making sure to pass the key:

We check for null value, in which case we return null. Otherwise we use the fromJson() method of the Gson class to get our object.

Here’s the code:

Leave a Reply

Your email address will not be published. Required fields are marked *

X