Search code examples
androidrealmunsupportedoperation

Copying to List initialized with Realm DB findAll() throws UnsupportedOperationException


When I try to add item to List initialized with Realm fetch, it throws UnsupportedOperationException. This is my code below:

private List<MessageModel> chatMessages;

void initializeChat() {
    chatMessages = realm.where(MessageModel.class)
            .equalTo("theMainTopidId", getMainTopicModel().getRadomUdid())
            .findAllSorted("updatedTime", Sort.DESCENDING);
    Log.e(TAG, "MessageModelSize1: " + chatMessages.size());
    mAdapter = new GroupMessageDetailsAdapter(this, chatMessages, realm);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setAdapter(mAdapter);
}

FetchMessage.sendMessage(PrefUtil.getUserInfo(this), theRootMessage, replyText, new MessageReplyListener() {
        @Override
        public void onSendMessage(Message sentMessage) {
            //Log.e(TAG, sentMessage.content);
            realm.beginTransaction();
            MessageModel messageModel = MessageModel.saveMessageToDb(sentMessage);
            messageModel.setTheMainTopidId(getMainTopicModel().getRadomUdid());
            realm.copyToRealm(messageModel);
            realm.commitTransaction();

            //Log.e(TAG, chatMessages.toString());
            chatMessages.add(messageModel); <======= Where the error is comming from
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public void onMessageSendFail(Exception e) {
            e.printStackTrace();
        }
    });

And the Error:

 java.lang.UnsupportedOperationException
 at io.realm.RealmResults.add(RealmResults.java:576)
 at io.realm.RealmResults.add(RealmResults.java:63)
 at   MessageDetailsActivity$2.onSendMessage(MessageDetailsActivity.java:294)
 at AsynchronousCalls.Group.Messages.FetchMessage$2 $1.run(FetchMessage.java:59)
 at android.os.Handler.handleCallback(Handler.java:739)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:148)
 at android.app.ActivityThread.main(ActivityThread.java:5417)
 at java.lang.reflect.Method.invoke(Native Method)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Solution

  • RealmResults is a list of elements for query results, so as the doc says, you cannot add an element to it.

    From the source code I can see the messageModel has been saved to the Realm db, so the only thing you need to do is use RealmChangeListener to call notifyDataSetChanged(). The RealmResults will be automatically updated at that point.

    See https://realm.io/docs/java/latest/#notifications