avoid NPE in onLoadMore

For v21.0.0, the following crash was reported:

Exception java.lang.NullPointerException: null cannot be cast to non-null type com.nextcloud.talk.chat.data.model.ChatMessage
  at com.nextcloud.talk.chat.ChatActivity.onLoadMore (ChatActivity.kt:3107)
  at com.stfalcon.chatkit.messages.MessagesListAdapter.onLoadMore (MessagesListAdapter.java:148)
  at com.stfalcon.chatkit.messages.RecyclerScrollMoreListener.onScrolled (RecyclerScrollMoreListener.java:82)
  at androidx.recyclerview.widget.RecyclerView.dispatchOnScrolled (RecyclerView.java:5688)
  at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep3 (RecyclerView.java:4741)
  at androidx.recyclerview.widget.RecyclerView.dispatchLayout (RecyclerView.java:4367)
  at androidx.recyclerview.widget.RecyclerView.onLayout (RecyclerView.java:4919)

This is now improved:
- lastOrNull prevents exceptions if no matching item is found
- as? is a safe cast that returns null if the cast fails

Whole expression becomes null-safe, and id will be null if anything along the way doesn't match. Only when not null, onLoadMore continues.

Signed-off-by: Marcel Hibbe <dev@mhibbe.de>
This commit is contained in:
Marcel Hibbe 2025-04-14 14:21:51 +02:00
parent 14b6060500
commit d0190158d5
No known key found for this signature in database
GPG Key ID: C793F8B59F43CE7B

View File

@ -2818,22 +2818,24 @@ class ChatActivity :
DateFormatter.isSameDay(message1.createdAt, message2.createdAt)
override fun onLoadMore(page: Int, totalItemsCount: Int) {
val id = (
adapter?.items?.last {
it.item is ChatMessage
}?.item as ChatMessage
).jsonMessageId
val messageId = (
adapter?.items
?.lastOrNull { it.item is ChatMessage }
?.item as? ChatMessage
)?.jsonMessageId
messageId?.let {
val urlForChatting = ApiUtils.getUrlForChat(chatApiVersion, conversationUser?.baseUrl, roomToken)
chatViewModel.loadMoreMessages(
beforeMessageId = id.toLong(),
beforeMessageId = it.toLong(),
withUrl = urlForChatting,
withCredentials = credentials!!,
withMessageLimit = MESSAGE_PULL_LIMIT,
roomToken = currentConversation!!.token
)
}
}
override fun format(date: Date): String =
if (DateFormatter.isToday(date)) {