Android Realm - Accessing Realm Object from Service

北慕城南 提交于 2019-12-01 06:18:44

You can try to use realm.copyFromRealm(youRealmObject);. These method copy Realm data into normal Java objects and detaching them from Realm.

Here is the example of usage:

youRealmObject = realm.copyFromRealm(youRealmObject);

Here is the information about it from docs:

Makes a standalone in-memory copy of an already persisted RealmObject. This is a deep copy that will copy all referenced objects. The copied object(s) are all detached from Realm so they will no longer be automatically updated. This means that the copied objects might contain data that are no longer consistent with other managed Realm objects. WARNING: Any changes to copied objects can be merged back into Realm using copyToRealmOrUpdate(RealmObject), but all fields will be overridden, not just those that were changed. This includes references to other objects, and can potentially override changes made by other threads.

https://realm.io/docs/java/latest/api/io/realm/Realm.html#copyFromRealm-E-

Technically you're supposed to open the Realm instance at the beginning of the background thread, close it at the end of execution in that background that, and pass it to methods in between.

public void handleIntent() { // or doInBackground etc
    Realm realm = null;
    try {
         realm = Realm.getDefaultInstance();
         .... 
         MyObj obj = realm.where(MyObj.class)
                          .equalTo(MyObjFields.ID, myObjId)
                          .findFirst(); // get by id
         .... 
    } finally {
         if(realm != null) {
              realm.close(); // important 
         } 
    } 
} 

Using realm.copyFromRealm() is a workaround, not a solution.


With AS 3.0, you can actually use try-with-resources no matter what your minSDK is (just like if you were using Retrolambda):

public void handleIntent() { // or doInBackground etc
    try(Realm realm = Realm.getDefaultInstance()) {
         .... 
         MyObj obj = realm.where(MyObj.class)
                          .equalTo(MyObjFields.ID, myObjId)
                          .findFirst(); // get by id
         .... 
    } // auto-close
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!