0

当我尝试将项目添加到使用fetchList初始化时,它会抛出. 这是我下面的代码:RealmUnsupportedOperationException

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();
        }
    });

和错误:

 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)
4

1 回答 1

2

RealmResults是查询结果的元素列表,因此正如文档所说,您不能向其中添加元素。

从源代码中我可以看到messageModel已经保存到 Realm 数据库中,所以您唯一需要做的就是使用RealmChangeListener来调用notifyDataSetChanged(). 届时RealmResults将自动更新。

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

于 2016-07-13T02:35:36.763 回答