Kotlin parcelable class 抛出 ClassNotFoundException

Kotlin parcelable class throwing ClassNotFoundException

我有一个 class 用作 RecyclerView 的数据模型,以便通过 activity 将此 class 的对象从一个 activity 传递到另一个 Intent 我必须做到 Parcelable

现在的问题是我能够将对象从一个 activity 发送到另一个并检索它,这样应用程序就不会崩溃,但是一直在 logcat 屏幕中抛出 ClassNotFoundException

我做错了什么?

----> Person.kt

@Parcelize
class Person(var name: String, var username: String, var address: String, val avatar: Int) : Parcelable

----> 在MainActivity.kt

val intent = Intent(this, ProfilePage::class.java)
        intent.putExtra("clicked_person",person)
        startActivity(intent)

---->。 onCreate() 在 ProfilePAge.kt

var person  = intent.getParcelableExtra<Person>("clicked_person") as Person

还有 Exception

E/Parcel: Class not found when unmarshalling: com.example.testkot.kotlinapp.Person
                                         java.lang.ClassNotFoundException: com.example.testkot.kotlinapp.Person

请记住,该应用程序不会崩溃,它会继续运行,但会在 logcat

中显示异常

在评论中测试解决方案后,以下工作没有抛出任何异常

通过Bundle

发送Parcelable
val intent = Intent(this, ProfilePage::class.java)
var bundle = Bundle()
bundle.putParcelable("selected_person",person)
intent.putExtra("myBundle",bundle)
startActivity(intent)

恢复中Parcelable

val bundle = intent.getBundleExtra("myBundle")
var person  = bundle.getParcelable<Person>("selected_person") as Person

但是,我不知道问题中我的旧代码有什么不同,为什么旧​​代码会抛出异常,而新代码不会抛出异常

为了方便您使用 Kotlin Parceables 时没有任何警告,我准备了以下扩展函数。

fun Intent.putParcel(key: String = "parcel_key", parcel: Parcelable) {
    val bundle = Bundle()
    bundle.putParcelable(key, parcel)
    this.putExtra("parcel_bundle", bundle)
}

fun <T : Parcelable> Intent.getParcel(key: String = "parcel_key"): T? {
    return this.getBundleExtra("parcel_bundle")?.getParcelable(key)
}

用法:

//Put parcel
intent.putParcel(parcel = Person()) //any Parcalable

//Get parcel
val person: Person?  = intent.getParcel() //auto converts using Generics
var bundle = intent.extras
var person = bundle.getParcelable<Person>("selected_person")

上面的代码对我有用。您可以缩短代码如下。

var person = intent.extras.getParcelable<Person>("selected_person")

我想这是目前 Kotlin 和 Java 之间的兼容性问题。 我找到了一个简单的解决方案,它只允许使用 Kotlin 而没有样板文件。

val intent = Intent(this, ProfilePage::class.java).apply {
    extras?.putParcellable("clicked_person",person)
}

startActivity(intent)

然后检索您应该使用的值:

var person = intent?.extras?.getParcellable<Person>("clicked_person")

注意:您不需要转换为人物

第Activity:

 val intent = Intent(this@MainActivity, DetailsActivity::class.java)
        intent.putExtra(Const.SELECTED_NOTE, noteList[position])
        startActivity(intent)

第二个Activity:

val note = intent.getParcelableExtra<Note>(Const.SELECTED_NOTE)

EXPLAIN: 首先你应该输入Parcelable数据然后在接下来的activity中调用getParcelableExtra! 在 getParcelableExtra 你应该调用 Data class (这里是 Note )和 Key Of Bundle (这里是 Const.SELECTED_NOTE)!