Issue
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
}
Solution
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
}
}
Answered By - Naimul Kabir
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.