问题描述
所以我有一个示例应用程序,它当前正在使用 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:尝试在空对象引用上调用接口方法“int java.util.List.size()” 在 com.example.myapplication.models.Character.writetoParcel(未知来源:85)
我还是个新手,所以我真的需要你的帮助。谢谢!
解决方法
很明显,数据类的列表引用导致的错误是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