Search code examples
javarealmrealm-list

How to convert RealmResults<Model> to ArrayList<Model>?


When I use realm.where(Model.class) it returns RealmResults and list item's fields are empty. How to convert queryset to readable ArrayList or iterate over RealmResults to get actual data from objects in DB?


Solution

  • All fetches are lazy in Realm, and the data is never copied. So if you want to get current data from RealmResults, you must call realm.copyFromRealm(results).

    public List<Model> getModelList() {
        List<Model> list = new ArrayList<>();
        Realm realm;
        try {
            realm = Realm.getDefaultInstance();
            RealmResults<Model> results = realm
                    .where(Model.class)
                    .findAll();
            list.addAll(realm.copyFromRealm(results));
        } finally {
            if (realm != null) {
                realm.close();
            }
        }
        return list;
    }