Android Kotlin Parcelize example

The Kotlin Parcelize became stable in kotlin 1.3.40, by upgrading the Kotlin version to 1.3.40 in the gradle, the Kotlin Parcelize extension will be available without specifying

androidExtensions {
    experimental = true
}

Here is an example of using Kotlin Parcelize to make data class parcelable and send the parcelable object between activities in Android. All you have to do is just to add the annotation @Parcelize at the top of the data class and make the data class to extend from Parcelable.

Here is a data class Car.kt

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

@Parcelize
data class Car(val color: String, val weight: Int, val make: Make): Parcelable

Here is a data class Make.kt

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

@Parcelize
data class Make(val name: String, val country: String): Parcelable

Here is an example for sending a Parcelable to a new activity.

val car = Car(
    color = "Yellow",
    weight = 3900,
    make = Make("Ford", "USA")
)

val intent = Intent(this, CarDetailActivity::class.java)
intent.putExtra(CAR, car)
startActivity(intent)

Here is an example for receiving the Parcelable in the receiver activity.

class CarDetailActivity: AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_car_detail)

        val car = intent.extras.getParcelable(CAR)
        tv_car_detail.text = car.toString()

    }

}

Complete example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search