Android Realm - Accessing Realm Object from Service

后端 未结 2 1005
野趣味
野趣味 2021-01-13 19:54

I have a realm object that is created in my activity. I need to be able to access this object within a service that I created. However I\'m getting the error when creating t

2条回答
  •  醉酒成梦
    2021-01-13 20:30

    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
    } 
    

提交回复
热议问题