How to Pass custom object via intent in kotlin

Ankit Kumar picture Ankit Kumar · Dec 1, 2017 · Viewed 52k times · Source
fun launchNextScreen(context: Context, people: People): Intent {
    val intent = Intent(context, NextScreenActivity::class.java)
    intent.putExtra(EXTRA_PEOPLE, (Parcelable) people)
    //intent.putExtra(EXTRA_PEOPLE, people as Parcelable)
    //intent.putExtra(EXTRA_PEOPLE, people)
    // tried above all three ways
    return intent
}

I tried the above code to pass an instance of the People class via intent using kotlin, but I am getting an error. What am I doing wrong?

Answer

A. Shevchuk picture A. Shevchuk · Dec 1, 2017

First, make sure the People class implements the Serializable interface:

class People : Serializable {
    // your stuff
}

Inner fields of People class must also implement the Serializable interface, otherwise you'll get runtime error.

Then it should work:

fun launchNextScreen(context: Context, people: People): Intent {
    val intent = Intent(context, NextScreenActivity::class.java)
    intent.putExtra(EXTRA_PEOPLE, people)
    return intent
}

To receive people back from Intent you'll need to call:

val people = intent.getSerializableExtra(EXTRA_PEOPLE) as? People