From d0190158d512e3ad0124cce9d6bd17946c49f547 Mon Sep 17 00:00:00 2001 From: Marcel Hibbe Date: Mon, 14 Apr 2025 14:21:51 +0200 Subject: [PATCH] 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 --- .../com/nextcloud/talk/chat/ChatActivity.kt | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt b/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt index 1dc84bf10..00dea1041 100644 --- a/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt +++ b/app/src/main/java/com/nextcloud/talk/chat/ChatActivity.kt @@ -2818,21 +2818,23 @@ 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 - val urlForChatting = ApiUtils.getUrlForChat(chatApiVersion, conversationUser?.baseUrl, roomToken) + messageId?.let { + val urlForChatting = ApiUtils.getUrlForChat(chatApiVersion, conversationUser?.baseUrl, roomToken) - chatViewModel.loadMoreMessages( - beforeMessageId = id.toLong(), - withUrl = urlForChatting, - withCredentials = credentials!!, - withMessageLimit = MESSAGE_PULL_LIMIT, - roomToken = currentConversation!!.token - ) + chatViewModel.loadMoreMessages( + beforeMessageId = it.toLong(), + withUrl = urlForChatting, + withCredentials = credentials!!, + withMessageLimit = MESSAGE_PULL_LIMIT, + roomToken = currentConversation!!.token + ) + } } override fun format(date: Date): String =