当我尝试将项目添加到使用List
fetch初始化的Realm
时,会抛出UnsupportedOperationException
。这是我的代码:
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)
答案 0 :(得分:2)
RealmResults
是查询结果的元素列表,因此doc表示,您无法向其中添加元素。
从源代码中我可以看到messageModel
已保存到Realm数据库中,因此您唯一需要做的就是使用RealmChangeListener
来调用notifyDataSetChanged()
。 RealmResults
将在此时自动更新。