将RealmChangeListener添加到使用copyToRealmOrUpdate创建的对象

时间:2018-08-23 13:31:10

标签: android realm

我有一个消息传递应用程序,该应用程序使用 RealmDB 为用户存储消息和线程。消息线程为RealmObjects。我正在尝试弄清楚如何添加一个RealmChangeListener,它将在更新(即收到新消息)中的任何线程时触发。首先通过 API 中的 syncMessages 函数从我的MessageThreadList活动中检索并随后更新线程。看来无论我在哪里添加

  

无法从非托管对象添加侦听器

错误。
我的代码:

MessageThread.java

public class MessageThread extends RealmObject {

    //Some member variables here - Id, title, etc

    //This is the field that would indicate a new message if changed
    private Date mLatestSentTimeStamp;

    //Empty constructor
    public MessageThread() { }


    public MessageThread(JSONObject jsonOb) {
        //Filling fields from JSON here
    }
}  

ThreadListActivity.java

public class ThreadListActivity {

    private Realm realm;

    @Override
    public void onCreate() {
        Realm.init();
        realm = Realm.getDefaultInstance();
        MyAPI.syncMessages();
    }  

MyAPI.java

static protected void syncMessages() {
    Realm realm = Realm.getDefaultInstance();
    realm.beginTransaction();

    JSONArray jsonMsgThreads = getJSONFromServer();
    for (int i = 0; i < jsonMsgThreads.length(); i++) {
        MessageThread m = new MessageThread(jsonMsgThreads.getJSONObject(i));
        realm.copyToRealmOrUpdate(m);
    }
    realm.commitTransaction();
}  

如果无法在此处添加它,我可以做些什么来在每个MessageThread上都有一个侦听器?

1 个答案:

答案 0 :(得分:0)

public class ThreadListActivity {

    private Realm realm;
    private RealmResults<MessageThread> messageThreads;

     @Override
     public void onCreate(Bundle bundle) {
         super.onCreate(bundle);
         Realm.init(this);
         realm = Realm.getDefaultInstance();
         messageThreads = realm.where(MessageThread.class).findAll();
         messageThreads.addChangeListener((results) -> {
            // any message thread was modified 
         } 
         MyAPI.syncMessages();
    }