5

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?

1

4 Answers 4

8

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.

7

For anyone working with jetpack-compose this problem is due to rememberSavable(), use remember() or store the value in a viewModel

1

Your class need to be Parcelable or Serializable. There is a jet-brains plugin you can use to generate an implementation (or you can use an experimental feature Parcelize).

Serializable is usually less complex, and may be all that you need.

0

Using Java Just Your Class should implement Parcelable and whit method : writeToParcel(Parcel parcel, int i)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.