How to convert RealmResults<Object> to List<Object>

允我心安 提交于 2019-11-30 22:26:39

问题


I have RealmResults that I receive from Realm like

RealmResults<StepEntry> stepEntryResults = realm.where(StepEntry.class).findAll();

Now I want convert RealmResults<StepEntry> to ArrayList<StepEntry>

I have try

 ArrayList<StepEntry> stepEntryArray = new ArrayList<StepEntry>(stepEntryResults));

but the item in my ArrayList is not my StepEntry object, it is StepEntryRealmProxy

How can I convert it? Any help or suggestion would be great appreciated.


回答1:


To eagerly read every element from the Realm (and therefore make all elements in the list become unmanaged, you can do):

 List<StepEntry> arrayListOfUnmanagedObjects = realm.copyFromRealm(realmResults);

But you generally have absolutely no reason to do that unless you want to serialize the objects with GSON (specifically, because it reads field data with reflection rather than with getters), because Realm was designed in such a way that the list exposes a change listener, allowing you to keep your UI up to date just by observing changes made to the database.




回答2:


The answer by @EpicPandaForce works well. I tried this way to optimize my app performance and I find the following is a bit faster. Another option for people who prefer speed:

RealmResults<Tag> childList = realm.where(Tag.class).equalTo("parentID", id).findAll();
Tag[] childs = new Tag[childList.size()];
childList.toArray(childs);
return Arrays.asList(childs);



回答3:


In Kotlin:

var list : List<Student>: listof()
val rl = realm.where(Student::class.java).findAll()

// subList return all data contain on RealmResults
list = rl.subList(0,rl.size)


来源:https://stackoverflow.com/questions/40758854/how-to-convert-realmresultsobject-to-listobject

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!