【发布时间】:2021-08-13 23:55:42
【问题描述】:
所以我有一个示例应用程序,它当前正在使用 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(Unknown Source:85)
我还是新手,所以我真的需要你的帮助。谢谢!
【问题讨论】:
标签: kotlin android-intent android-recyclerview nullpointerexception parcelable