Realm-java: List<E> to RealmList<E>

Created on 9 Jul 2015  Â·  5Comments  Â·  Source: realm/realm-java

Sorry if this is noob question, but I just ran into this issue...

Say I have a bunch of objects in ArrayList<MyObject> list and I want to add it to my other realm object, how do I do that?

class OtherObject extends RealmObject {
    private RealmList<MyObject> list;
    // setter & getter
}

How to add that ArrayList to OtherObject.setList(RealmList<MyObject> list)?

I've tried RealmList<MyObject> realmList = (RealmList<MyObject>) realm.copyToRealm(list) but got cast exception.

Thanks.

T-Help

Most helpful comment

Also this should work and save some memory:

realm.beginTransaction();
OtherObject.getList().addAll(list);
realm.commitTransaction();

All 5 comments

I think I should use new RealmList<E>(list.toArray(arr))

Hi, I have a problem on how to convert a non-managed List to managed list and add it to OtherObject can you give a light here?

Try this:

realm.beginTransaction();
OtherObject.setList(new RealmList<YouModel>(list.toArray(new YouModel[list.size()])));
realm.commitTransaction();

Ya, now that works! I just realized the first time I added the unmanaged RealmList to managed RealmObject and got NPE (so I reopened the issue)

Also this should work and save some memory:

realm.beginTransaction();
OtherObject.getList().addAll(list);
realm.commitTransaction();
Was this page helpful?
0 / 5 - 0 ratings

Related issues

jjorian picture jjorian  Â·  3Comments

yuwu picture yuwu  Â·  3Comments

AlbertVilaCalvo picture AlbertVilaCalvo  Â·  3Comments

bryanspano picture bryanspano  Â·  3Comments

CNyezi picture CNyezi  Â·  3Comments