I have a RealmResults <Student> object. I want to convert it to RealmList <Student> object. any suggestions?
10 Answers
RealmResults is returned if a query is expected to give a collection of objects (e.g. RealmQuery<E>.findAll()). Otherwise, single object queries will return a RealmObject.
Managed and Unmanaged ObjectsRealmResults are managed objects, meaning they cannot be manipulated outside of Realm transactions and are confined in the thread that created them. Converting RealmResults into a RealmList will make the data unmanaged, as what @epicpandaforce pointed out, meaning the objects in the list are not connected to the database anymore and are basically normal Java objects which can be transferred in between threads and manipulated.
To convert RealmResults to a RealmList:
RealmResults<User> results = realm.where(User.class).findAll();
RealmList<Users> users = realm.copyFromRealm(results);
Changes to an unmanaged object will not in any means affect the original in the database unless a realm.copyToRealm(users), doing the opposite of copyFromRealm(), is executed after. Keep in mind that RealmLists can be managed or unmanaged, as a RealmObject from a RealmResult can have the following structure in which the RealmList in this case is a managed object:
class User {
int id;
String name;
RealmList<String> petNames;
}
Finally, copyFromRealm() returns a List so it's also possible to do
ArrayList<User> users = realm.copyFromRealm(results);
Realm has some new features check-in documentation Realm Documentation
Realm has copyfromRealm function which we can use to convert the result to list
RealmList<Student> student=realm.copyfromRealm(Realmresult);
@JemshitIskenderov This should copy for you.
public RealmList<Student> convertResultToList(RealmResult<Student> realResultsList){
RealmList <Student> results = new RealmList<Student>();
for(Student student : realResultsList){
results.add(copy(student));
}
}
private Student copy(Student student){
Student o = new Student();
o.setCreated(student.getCreated());
o.setModified(student.getModified());
o.setDeleted(student.getDeleted());
o.setName(student.getName());
//List more properties here
return o;
}
Code:
public class RealmCollectionHelper {
public static <C extends RealmModel> RealmList<C> mapperCollectionToRealmList(Collection<C> objects){
if (objects == null){
return null;
}
RealmList<C> realmList = new RealmList<>();
realmList.addAll(objects);
return realmList;
}
}
Here my gist: https://gist.github.com/jmperezra/9b4708051eaa2686c83ebf76066071ff