在 Intent Kotlin 中传递 Parcelable 时尝试在空对象引用上调用接口方法 'int java.util.List.size()'

Attempt to invoke interface method 'int java.util.List.size()' on a null object reference on passing Parcelable in Intent Kotlin

所以我有一个示例应用程序,目前正在使用 Retrofit 来获取数据并使用其自定义适配器将其显示在 recyclerview 中。我想在我的 recyclerView 上单击角色名称时将数据传递到更多详细信息页面。我找到了一些教程并决定像这样使用 Parcelize 注释:

@Parcelize data class Character (
val charID: Long,
val name: String,
val birthday: String,
val occupation: List<String>,
val img: String,
val status: String,
val nickname: String,
val appearance: List<Long>,
val portrayed: String,
val category: String,
val betterCallSaulAppearance: List<Long> ) : Parcelable

我的适配器看起来像这样:

override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    val character = characters[position]
    holder.characterNameText.text = character.name

    holder.characterNameText.setOnClickListener {
        holder.passData(character)
    }
}

override fun getItemCount() = characters.size


class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView) {
    val characterNameText = itemView.findViewById<TextView>(R.id.character_name)

    fun passData(character : Character) {
        val intent = Intent(itemView.context, CharacterDetails::class.java)
        intent.putExtra(CHARACTER, character)
        itemView.context.startActivity(intent)
    }



}

并且在 CharacterDetails Activity 中它看起来像这样:

companion object {
    const val CHARACTER = "character"
}
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_character_details)

    val bundle = intent.extras
    val character = bundle!!.getParcelable<Character>(CHARACTER)


    val characterName = findViewById<TextView>(R.id.character_details_name)

然而我得到了

java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference at com.example.myapplication.models.Character.writeToParcel(Unknown Source:85)

我还是个新手,所以我真的需要你的 help.Thanks!

很明显,数据class的列表引用导致的错误为null。您可以这样修改代码。

@Parcelize data class Character (
val charID: Long,
val name: String,
val birthday: String,
val occupation: List<String>?,
val img: String,
val status: String,
val nickname: String,
val appearance: List<Long>?,
val portrayed: String,
val category: String,
val betterCallSaulAppearance: List<Long>? ) : Parcelable