Parcelable 在 kotlin 中无法正常工作

Parcelable isn't working properly in kotlin

我从 StartActivity 发送 sendDataResultActivity

val sendData = SendData(10, "xyz", "yss")
sendData.e = 933
sendData.f = "hello"
sendData.g = 39

// Log.d("A", "${sendData.toString}")
val intent = Intent(this@StartActivity, ResultActivity::class.java)
intent.putExtra(RESULT_DATA, sendData)
startActivity(intent)
sendData = intent.extras!!.getParcelable(RESULT_DATA)
// Log.d("B", "${sendData.toString}")

模型 class 看起来像这样。

@Parcelize
data class SendData(var a: Int, var b: String, var c: String) : Parcelable {
    var e: Int? = null
    var f: String? = null
    var g: Int? = null
    
    var isClicked = false

    override fun toString(): String{
        return JsonUtil.toJson(this) // custom util
    }
}

但是当我检查 Log-A、Log-B 时。

// Log-A
{
   "a": 10,
   "b": "xyz",
   "c": "yss",
   "e": 933,
   "f": "hello",
   "g": 39,
   "isClicked": false
}

// Log-B
{
   "a": 10,
   "b": "xyz",
   "c": "yss",
   "isClicked": false
}

所以,定义为Nullable的成员传递后为null。 这段代码有什么问题?

@Parcelize 的工作方式是它仅 serializes/deserializes 主构造函数中的属性。您只在主构造函数中声明了属性 abc。因此,编译器只会将 abc 的值插入到生成的 Parcel 中,当然,只有这些值会在接收端解组.

您需要将其他属性添加到主构造函数中,或者自己实现 Parcelable 接口而不是使用 @Parcelize.

https://joaoalves.dev/posts/kotlin-playground/parcelable-in-kotlin-here-comes-parcelize/

另请参阅此 以及答案中的各种建议

@Parcelize requires all serialized properties to be declared in the primary constructor. The plugin issues a warning on each property with a backing field declared in the class body. Also, you can't apply @Parcelize if some of the primary constructor parameters are not properties.

来自https://developer.android.com/kotlin/parcelize 您必须将 e、f 和 g 变量声明移至主构造函数 你的模型代码可以是这样的:

@Parcelize
data class SendData(var a: Int, var b: String, var c: String, var e: Int? = null, var f: String? = null, var g: Int? = null) : Parcelable { 
    var isClicked = false

    override fun toString(): String{
        return JsonUtil.toJson(this) // custom util
    }
}