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

Vassily picture Vassily · May 16, 2016 · Viewed 11.3k times · Source

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?

Answer

DH28 picture DH28 · Dec 22, 2016

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;
}