首页 > 解决方案 > 尝试在包含空字段的 ArrayList 变量上使用 parcelable 时出现 kotlin.TypeCastException

问题描述

我昨天真的开始使用 Kotlin,所以我仍然很难理解基本原理。我想通过意图将一个对象发送到另一个活动并在该对象上实现 parcelable。该对象包含一些 MutableLists,格式如下:

var favoritePlaces: MutableList<String?>? = null

我使用这个方法构造函数来打包它:

constructor(`in`: Parcel) {
  `in`.readList(favoritePlaces, String::class.java.classLoader)
}

这是我在 Android Studio 中遇到的错误,因为存在类型不匹配:

安卓工作室错误

我试图接受 Android Studio 的建议,在构造函数中留下了这个:

constructor(`in`: Parcel) {
   `in`.readList(favoritePlaces as List<*>, String::class.java.classLoader)
 }

在 writeToParcel 方法中:

override fun writeToParcel(dest: Parcel, flags: Int) {
    dest.writeList(favoritePlaces as List<*>?)
}

但是当我尝试使用它时,我在启动 Activity 时收到以下错误消息:

java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.test.app.Activity}: kotlin.TypeCastException: null 不能转换为非 null 类型 kotlin.collections.List<*>

我确实了解 kotlin.collections.List<*> 类型是非空类型,并且由于我的数组中有一些空字段,因此发生此错误是有道理的。我现在的问题是,如何在 Kotlin 中用非空字段和空字段打包字符串数组???

标签: androidkotlinarraylistparcelable

解决方案


readList需要一个非空参数列表,它将向其中添加元素,因此您需要在调用之前对其进行初始化readList

favoritePlaces = mutableListOf<String?>()
`in`.readList(favoritePlaces as List<*>, String::class.java.classLoader)

或更好,

favoritePlaces = `in`.createStringArrayList()

但在 Kotlin 中,基本上没有理由手动执行此操作;如果可能,请改用@Parcelize(您需要将属性移动到主构造函数而不是类主体)。


推荐阅读