android - 尝试在包含空字段的 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 中用非空字段和空字段打包字符串数组???
解决方案
readList
需要一个非空参数列表,它将向其中添加元素,因此您需要在调用之前对其进行初始化readList
:
favoritePlaces = mutableListOf<String?>()
`in`.readList(favoritePlaces as List<*>, String::class.java.classLoader)
或更好,
favoritePlaces = `in`.createStringArrayList()
但在 Kotlin 中,基本上没有理由手动执行此操作;如果可能,请改用@Parcelize
(您需要将属性移动到主构造函数而不是类主体)。
推荐阅读
- c++ - 生成带有顶点和索引的球体?
- docker - AWS ECS(EC2启动类型),Nest js中的docker容器TCP通信
- c++ - 在类中初始化 unique_ptr
- jupyter-notebook - 如何使用此 python 代码解决关键错误?
- amazon-web-services - 如果我不添加默认变量,则 Terraform/Terragrunt 错误
- python - Django 3:无法生成动态对象视图
- html - 动画旋转框 css 关键帧
- node.js - 如何在 MongoDB 中相互比较文档?
- c# - 从蛇案到骆驼案的对象序列化
- python - Pyspark Mutlipe 数据框初始化