Skip to content

Saving an Object to SharedPreferences(with GSON)

Android, SharedPreferences, Kotlin1 min read

SharedPreferences in Android provides a simple way to store key-value pairs locally on a device even after the application is closed. While it is commonly used for storing primitive data types like integers or strings, you might encounter scenarios where you need to save more complex objects. In this tutorial, we will explore how to save an object to SharedPreferences in Android using Kotlin, with a focus on integrating the GSON library for object conversion. Also remember - using SharedPreferences for large amounts of data isn't always the best decision so keep that in mind while reading.

Setting Up SharedPreferences

Before we dive into saving objects, let's set up the SharedPreferences instance in our Android application. First, make sure to initialize SharedPreferences in your activity or fragment:

1val sharedPref = context.getSharedPreferences("my_preferences", Context.MODE_PRIVATE)
2val editor = sharedPref.edit()

Adding GSON to Your Project

To use GSON for converting objects to JSON and vice versa, you first need to add it to your project. GSON is a powerful library by Google that simplifies serialization and deserialization of Java objects.

  1. Open your project's build.gradle file (Module: app).
  2. Add the GSON library dependency in the dependencies section:
1implementation ''
  1. Sync your project with Gradle files to ensure the library is properly included.

Converting Object to JSON

To save an object to SharedPreferences, we first need to convert it to a JSON string since SharedPreferences can only store primitive data types. This is where GSON comes into play, as it greatly simplifies the process.

Assuming we have a data class named User that we want to save:

1data class User(val id: Int, val name: String)

Convert an object of this class to a JSON string as follows:

1val user = User(1, "Alice")
2val gson = Gson()
3val json = gson.toJson(user)

Saving Object to SharedPreferences

With the object converted to a JSON string, proceed to save it to SharedPreferences. Utilize the putString method to store the JSON string with a specific key:

1editor.putString("user_data", json)

Retrieving Object from SharedPreferences

To retrieve the saved object, reverse the process. Retrieve the JSON string from SharedPreferences and then deserialize it back to the original object:

1val jsonString = sharedPref.getString("user_data", "")
2val user = gson.fromJson(jsonString,

Wrapping Up

In this article, we explored how to save an object to SharedPreferences the GSON library(for JSON encoding). By converting the object to a JSON string and storing it as a key-value pair, we can effectively persist complex data structures locally on the device. Integrating GSON simplifies serialization and deserialization, making it a straightforward process to manage complex data in SharedPreferences. Happy coding!