Android Studio 0
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.
Then having created our application class we can now come and save and load our json data.
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
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
Then obtain a
SharedPreference.Editor object by invoking the
edit() method of our
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
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
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: