Passing Objects Between Activities with Gson

A quick look at using Gson in Kotlin to pass objects between activities

Intents are easy to use when you need to pass primitive data types from one activity to another. But what about when you want to pass objects between activities?

You still use intents, but the object needs to be transformed into something that can be added to an intent.

When working on the Punch Buggy app, I needed to pass a Player object from one activity to another. To do this I used the Gson Library.

With Gson you can convert an object to JSON. You can then pass the JSON between activities with intents. We'll look at how to do this in Kotlin.

Setup

First, you need to add Gson as a dependency in your Gradle file:

dependencies {
  implementation 'com.google.code.gson:gson:2.8.6'
}


Sending the object

Once Gson is installed and ready to use, you can create a Gson object and call its toJson method. This method takes in one argument: the object you want to convert to JSON. In this example, it's foo.

val foo = Foo() // our custom object to send
val gson = Gson()
val passableObject = gson.toJson(foo)

We can now add passableObject to the intent with putExtra.

val intent = Intent(this, MainActivity::class.java)
intent.putExtra("name", passableObject)

passableObject is a JSON representation of our object, Foo, that is being sent to MainActivity.

Receiving the object

To receive the object inside of MainActivity we need to first get the string from the intent. If this is not null, then we can use Gson to convert the JSON back to our object using the fromJson method.

// receive the JSON from the intent
val incomingJson = getIntent().getStringExtra("name")

// if it's not null, get the object with gson
if (incomingJson != null) {
    val gson = Gson()
    
    // transform the JSON to our custom object
    val customObject = gson.fromJson(incomingJson, Foo::class.java)
}

What happened:

  1. We received the intent and got the value associated with name.
  2. If we got the JSON successfully, then we create a Gson object.
  3. Lastly we use fromJson to convert the JSON back to our Foo object. fromJson takes in two arguments: the JSON to convert and the target object to create.

Now we have successfully passed objects between activities!