简体   繁体   中英

Android Realm: No results when added in singleton

I'm testing out Realm for database storage.

I'm using a singleton for fetching and managing common data that needs to be refreshed fairly often. But it seems that the Realm defaultInstance that get in my singleton is not in the same scope as if I get it in my Activity. So when I fetch remote data via my singleton, then save to realm, I can't retrieve that data from an Activity (get an empty result set).

I have attempted to pass in the Realm instance I defined in the Activity to the singleton (and close it there as well), but I still cannot retrieve saved results via the Activity instance.

I'm setting the default configuration in my Application class if that makes a difference.

Any help would be appreciated in clearing this up.

**Edit

Here's some more code. I'm using retrofit and gson, and my relevant services are in a Utility class (which may be causing the issue).

 private void fetchMyObjects(Context context) {

        // Fetch the myObjects
        UtilityServices utilityServices = new UtilityServices(context);
        utilityServices.getMyObjects(new UtilityServices.MyObjectsListener() {
            @Override
            public void gotMyObjects(final ArrayList<MyObject> myObjects, Exception e) {
                if(e == null) {
                    Realm realm = null;
                    try {
                        realm = Realm.getDefaultInstance();
                        realm.executeTransaction(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                realm.delete(MyObject.class);
                                realm.copyToRealm(myObjects);
                                Log.v("qwer", "LocalDataFragment fetchMyObjects: " + realm.where(MyObject.class).findAll().size());
                            }
                        });
                    } finally {
                        if(realm != null) {
                            realm.close();
                        }
                    }
                } else {
                    // TODO: Handle a myObject error.
                    e.printStackTrace();
                }
            }
        });
    }

There is only one way that the results of a Realm transaction would not be visible after a transaction is executed and that is that the transaction takes place on a different thread.

It seems quite likely that this is the case, in your code, since, if getMyObjects ran on the UI thread, you would be getting the "no network activity on the UI thread exception"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM