Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 255
Vassily Avatar asked May 16 '16 09:05

Vassily


2 Answers

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;
}
like image 163
DH28 Avatar answered Nov 14 '22 15:11

DH28


RealmResults<E> implements the Iterable<E> interface, so you can iterate with:

for (E e : realmResults) {
    // Do stuff
}

If this does not answer the question, then please precise it and add a sample of code.

like image 27
T. Claverie Avatar answered Nov 14 '22 14:11

T. Claverie