【发布时间】:2022-01-03 09:41:12
【问题描述】:
我有一个小型聊天应用程序,我尝试将 Parcelable 用于我的项目,在调试项目之前没有任何错误。当我调试项目时,它会抛出一个错误
设置信息(聊天)
返回参与者.find { it.id != userId }!!.profilePicture
作为NullPointerException,不知为什么?有什么想法吗?
聊天活动:
val chat = intent.extras!!.getParcelable<Chat>("chat")!!
setInfo(chat)
configureRecycler(chat.messages)
private fun configureRecycler(messages: ArrayList<Message>) {
val user = userPresenter.getUser()
val messagesAdapter = MessagesAdapter(user.id, messages)
recycler_chat.apply {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(context)
adapter = messagesAdapter
}
}
用户:
import android.os.Parcelable;
import kotlinx.android.parcel.Parcelize
@Parcelize
class User(
val username: String?,
val profilePicture: String?
): BaseModel(), Parcelable {
constructor() : this("", "",)
}
聊天: 导入android.os.Parcelable; 导入 kotlinx.android.parcel.Parcelize
@Parcelize
class Chat(
val participantsId: ArrayList<String>,
): BaseModel(), Parcelable {
var participants = ArrayList<User>()
val messages = ArrayList<Message>()
fun getProfilePicture(userId: String): String? {
return participants.find { it.id != userId }!!.profilePicture
}
fun getChatName(userId: String): String? {
return participants.find { it.id != userId }!!.username
}
}
消息: 导入android.os.Parcelable; 导入 kotlinx.android.parcel.Parcelize
@Parcelize
class Message(
val ownerId: String,
val owner: User?
): BaseModel(), Parcelable {
val status: MessageStatus = MessageStatus.CREATED
}
【问题讨论】:
-
participants.find { it.id != userId }可以为 null 如果participants大小仅为 1 并且该项目是该用户 ID。你怎么这么肯定participants.size>1总是?您需要检查这些边缘情况。当您遇到异常时记录participants列表数据。即使在调试期间,您也可以评估表达式并找出其为 null 的原因。 -
@ADM,明白了,tnx 这么多
标签: android kotlin parcelable