Reputation: 13
I'm trying to pass a Serializable data class from one activity to another via intent, but Android Studio doesn't accept my data class as an argument. The editor says "None of the following functions can be called with the arguments supplied". If I try to cast my data class to Serializable, it says "this cast can never succeed". My data class:
@Serializable
data class MessageModel(
val timeStamp: String,
val body: String
)
And code for passing the extra to the intent:
val intent = Intent(this, MessageActivity::class.java)
val test = MessageModel("timeStamp", "message body")
intent.putExtra("A string for referencing", test)
startActivity(intent)
Second method I tried:
val intent = Intent(this, MessageActivity::class.java)
val test = MessageModel("timeStamp", "message body")
intent.putExtra("A string for referencing", test as Serializable)
startActivity(intent)
I've tried building from the terminal with gradle in case it was Android Studio acting up, but the same problem occurs.
Note: passing string extras works fine, it's just some problem with Serializable. I don't see what I'm doing wrong, every tutorial and thread I can find simply pass a Serializable object and it works. Any help is greatly appreciated!
Upvotes: 1
Views: 2147
Reputation: 21
One way to overcome this problem and still use Kotlin serializable is to use JSON encoding.
On the sending side, encode as follows
intent.putExtra("data", Json.encodeToString(object))
On the receiving side, decode as follows
override fun onReceive(context: Context, intent: Intent) {
val data = intent.getStringExtra("data")
val object = Json.decodeFromString<Object>(data)
}
Upvotes: 2
Reputation: 71
You should implement Serializeable, not annotate.
data class MessageModel( val timeStamp: String, val body: String ): Serializable
Upvotes: 5