【问题标题】:why it is throw error as NullPointerException when I using Parcelable for my project in Kotlin?为什么当我在 Kotlin 中为我的项目使用 Parcelable 时会抛出 NullPointerException 错误?
【发布时间】: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&gt;1总是?您需要检查这些边缘情况。当您遇到异常时记录participants 列表数据。即使在调试期间,您也可以评估表达式并找出其为 null 的原因。
  • @ADM,明白了,tnx 这么多

标签: android kotlin parcelable


【解决方案1】:

问题不在 Parcelable 中。检查两次是否正确传递了聊天可包裹对象。出于某种原因,聊天没有从之前的活动中传递过来。您可以通过使用安全调用运算符来避免错误。

val chat: Chat? = intent.extras?.getParcelable<Chat>("chat")

chat?.let{ it->
    setInfo(it)
    configureRecycler(it.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
    }
}

【讨论】:

  • 我现在明白了 tnx :)
猜你喜欢
  • 2020-11-19
  • 1970-01-01
  • 2014-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
相关资源
最近更新 更多