How to Pass custom object via intent in kotlin
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
Found a better way of doing this:
In your gradle:
apply plugin: 'org.jetbrains.kotlin.android.extensions'
android {
androidExtensions {
experimental = true
}
}
In your data class:
@Parcelize
data class Student(val id: String, val name: String, val grade: String) : Parcelable
In source activity:
val intent = Intent(context, Destination::class.java)
intent.putExtra("student_id", student)
context.startActivity(intent)
In destination activity:
student = intent.getParcelableExtra("student_id")
Parcelize
is no longer experimental, as of Kotlin 1.3.60+!
Define a data class, adding @Parcelize
annotation and extending Parcelable
:
@Parcelize
data class People(val id: String, val name: String) : Parcelable
To add to intent:
val intent = Intent(context, MyTargetActivity::class.java)
intent.putExtra("people_data", student)
context.startActivity(intent)
In MyTargetActivity
:
val people: People = intent.getParcelableExtra("people_data")
If you haven't yet, enable extensions in your app's build.gradle
. This also enables data binding and other great advanced features
apply plugin: 'kotlin-android-extensions'
Implement Serializable in the object:
data class Object (
var param1: Int? = null,
var param2: String? = null
) : Serializable
or
class Object : Serializable {
var param1: Int? = null,
var param2: String? = null
}
Then, you can pass the object using Intent:
val object = Object()
...
val intent = Intent(this, Activity2::class.java)
intent.putExtra("extra_object", object as Serializable)
startActivity(intent)
Finally, in Activity2 you get the object with:
val object = intent.extras.get("extra_object") as Object