提问人:Mr.LauLau 提问时间:5/26/2021 更新时间:5/26/2021 访问量:766
尝试在 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上的字符名称时,我想将数据传递到更详细的页面。我找到了一些教程,并决定像这样使用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 活动中,它如下所示:
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:尝试在空对象引用上调用接口方法“int java.util.List.size()” 在 com.example.myapplication.models.Character.writeToParcel(未知来源:85)
我还是新手,所以我真的需要你的帮助。谢谢!
答:
0赞
Future Deep Gone
5/26/2021
#1
显然,数据类的列表引用导致的错误是空的。您可以像这样修改代码。
@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
评论