Parcel: unable to marshal value
Asked Answered
J

4

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?

Joyce answered 23/8, 2017 at 13:5 Comment(1)
Possible duplicate of Android - Parcel: unable to marshal valueExtirpate
A
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.

Alexine answered 23/8, 2017 at 13:9 Comment(0)
B
7

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

Bereft answered 7/3, 2021 at 8:21 Comment(0)
Z
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.

Zacharia answered 23/8, 2017 at 13:16 Comment(0)
C
0

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

Crossstaff answered 24/12, 2017 at 11:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.