Android Kotlin: Use Parcelable to pass object to another activity

Hedy Tang
1 min readApr 2, 2019

--

As suggested in this article, https://www.3pillarglobal.com/insights/parcelable-vs-java-serialization-in-android-app-development, Parcelable has better performance than Serialization. Thus, I chose to use Parcelable to pass the object I want to another activity. Below are the implementation steps.

Step 1: Create a class for your object that implements Parcelable. Define required variables in your class. For mine, I only needed title and description. Because both of my variables are String, I will be using readString() and writeString() functions to receive value and write to parcel. You will need different functions for different data types and they can be found at, https://developer.android.com/reference/android/os/Parcel.

class ParcelObjectName(val title:String, val description:String) :Parcelable {

constructor(parcel: Parcel) : this(
parcel.readString(),
parcel.readString())

override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(title)
parcel.writeString(description)
}

override fun describeContents(): Int {
return 0
}

companion object CREATOR : Parcelable.Creator<ParcelObjectName> {
override fun createFromParcel(parcel: Parcel): ParcelObjectName {
return ParcelObjectName(parcel)
}

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

}

Step 2: Create the Parcel in the fragment or activity where you want to start the new activity:

val intent = Intent(this.activity, NewActivityName::class.java)
val bundle = Bundle()
val parcel = ParcelObjectName(titleValue,descriptionValue)


bundle.putParcelable("key", parcel)
intent.putExtra("Bundle", bundle)
startActivity(intent)

Step 3: Retrieving the Parcel from your new activity:

val bundle = intent.getBundleExtra("Bundle")
val object = bundle.getParcelable<ParcelObjectName>("key")

Step 4: Now you can access your data using object.attributeName. 🎉

--

--