Parcelable in Android: How to transfer data in-between ?

Are you new to Android ecosystem ? Or maybe you’re just trying to refresh you knowledge of Parcelable in Android.

Regardless this post has got you covered. You’ll see how easy it is to get things done using parcelable.

Before you begin

Here is a simple cautionary section before you blindly begin to copy paste the code from here.

There are two ways to accomplish what we are trying to do, all thanks to Kotlin. But the first approach will only work with Kotlin and only after a dependency insertion.

So if you’re more of a Java person. Then you might want to skip to the second method directly.

Using Kotlin Parcelable dependency

Alright, we have to add the kotlin-parcelize in the plugin section of our dependency like below.

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-parcelize' // include this line 
}Code language: Groovy (groovy)

The preview of the build.gradle file after the change is shown below.

build.gradle Parcelable in Android

Now we are all set to use Parcelable in Android. Let us see how we can use it.

For instance:

See below we have a class named Person that is going to be parcelized. Take note of the comments.

import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

@Parcelize // include this annotation
data class Person(
    val name: String,
    val age: Int,
    val phoneNumber: String,
    val country: String,
) : ParcelableCode language: Kotlin (kotlin)

You can now pass the object of this class between Fragments and Activities or anywhere using Bundles.

It’s really helpful if you want to quickly pass some simple objects. But when it comes to complicated objects. This approach might not be of much help.

That is where the actual implementation comes in. It will be a bit more complicated than adding a simple annotation.

But if you follow along it is not that hard.

Implementing Parcelable in Android

We can implement the parcelable first and then instead of using any additional dependency. We can create the implementation ourselves.

See the code below to get the idea.

data class Person(
    val name: String,
    val age: Int,
    val phoneNumber: String,
    val country: String,
) : Parcelable {

    /**
     * Create a constructor that will take in [Parcel].
     * You should pass in the data in same sequence.
     */
    constructor(parcel: Parcel) : this(
        parcel.readString() ?: "",
        parcel.readInt(),
        parcel.readString() ?: "",
        parcel.readString() ?: ""
    )

    /**
     * Here you need to put the data into the parcel using appropriate methods.
     * And you have to keep the ordering of the variables as they appear in the class.
     */
    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(name)
        parcel.writeInt(age)
        parcel.writeString(phoneNumber)
        parcel.writeString(country)
    }

    /**
     * You need this but leave it as is i.e return 0.
     */
    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<Person> {

        /**
         * We need to create 2 static methods out of which this is one.
         * This will be used to create a new instance of the Class by passing in the [Parcel]
         */
        override fun createFromParcel(parcel: Parcel): Person {
            return Person(parcel)
        }

        override fun newArray(size: Int): Array<Person?> {
            return arrayOfNulls(size)
        }
    }

}Code language: Kotlin (kotlin)

Make sure you follow the same order in the constructor and thewriteToParcel() method.

And that is it, you have just completed creating a parcelable implementation in Android.

Suggested:

Android Get Screen Width & Density in Pixels

Android Handler: Learn Everything About Handler

Push Notifications in Android Using One Signal

Show or Hide Soft Keyboard in Android Application And More

OnClickListener in Android RecyclerView: Example

Related Posts