0

I have small chat app and I try to use the Parcelable for my project, there is not any error until debug the project. When I debug the project it is throw an error for

setInfo(chat)

return participants.find { it.id != userId }!!.profilePicture

as NullPointerException, I do not know why? Any idea?

ChatActivity:

   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
        }
    }

User:

import android.os.Parcelable;
import kotlinx.android.parcel.Parcelize

  @Parcelize
  class User(
    val username: String?,
    val profilePicture: String?
): BaseModel(), Parcelable {
    constructor() : this("", "",)
}

Chat: import android.os.Parcelable; import 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

    }

  }

Message: import android.os.Parcelable; import kotlinx.android.parcel.Parcelize

@Parcelize
class Message(
    val ownerId: String,
    val owner: User?
): BaseModel(), Parcelable {
    val status: MessageStatus = MessageStatus.CREATED
   
}
  • 1
    `participants.find { it.id != userId }` can be null if `participants` size is only 1 and that one item is that userId. How are you so sure that `participants.size>1` always ? you need to check for these edge cases . Log the `participants` list data when you get the exception . Even during debugging you can evaluate the expression and find out why its null . – ADM Jan 03 '22 at 13:15
  • @ADM, understand , tnx so much –  Jan 03 '22 at 15:46

1 Answers1

0

The issue is not in Parcelable. Check twice if you are passing the chat parcelable object correctly or not. For some reason, chat is not being passed from the previous activity. You can avoid the error by using safe call operator.

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
    }
}
Naimul Kabir
  • 434
  • 6
  • 13