I'm using Kotlin with Anko and I want to send to another activity a list of Players.
class Player(var name: String?) {
var score: Int = 0
init {
this.score = 0
}
}
My activity:
class MainActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle ? ) {
btn.setOnClickListener {
val players = ArrayList <Player> ()
players.add(Player("John"))
players.add(Player("Jeff"))
startActivity <ScoreActivity> ("key" to players)
}
}
}
When the code reaches the startActivity line, I get this error:
java.lang.RuntimeException: Parcel: unable to marshal value com.yasin.myapp.Player@4e3940e
I suppose something is wrong with my class Player, but I don't know what. I'm using kotlin version 1.1.4. Someone can help me?
Your class should implement Parcelable
(or Serializable
, though Parcelable
is the advised one on Android) to be able to pass the objects across Activity using the Intent.
Using Kotlin 1.1.4 and Android Extensions Plugin, you can add @Parcelize
annotation to get the Parcelable
implementation.
@Parcelize
class Player(var name: String?) : Parcelable {
// ...
Refer the blog post.
This feature is covered as experimental, so you have turn on an experimental flag in your build.gradle file:
androidExtensions {
experimental = true
}
Another option is to use this plugin to generate the boilerplate code necessary for the Parcelable
implementation, but you should remember to update the implementation code everytime you change any properties in the class.
Or you can write your own Parcelable
implementation.