Using Realm for Android, I have a String[] objectIds
of unique IDs for some Realm objects. I'm trying to retrieve the corresponding Realm objects in the same order as the String[] objectIds
.
String[] objectIds = new String[]{"1", "10", "2", "3"};
RealmResults<MyRealmObject> myRealmObjects = realm.where(MyRealmObject.class).in("id", objectIds).findAll();
for(MyRealmObject obj: myRealmObjects) {
log(obj.id) //should print 1, 10, 2, 3
}
However, using .findAll() appears to re-order the results. How can I retrieve a list of objects using "in" and get the same ordering as the objectIds array? Is there a better way to approach this problem?
i.e. I want MyRealmObject.id == 1 to be the first result in the list, MyRealmObject.id == 10 to be the second result in the list, etc. (same as the objectIds array order).
It is not possible to write a simple query to do what you want. The best alternative is to do something like:
String[] objectIds = new String[]{"1", "10", "2", "3"};
RealmResults<MyRealmObject> myRealmObjects = realm.where(MyRealmObject.class).in("id", objectIds).findAll();
for (String id : objectIds) {
MyRealmObject obj = myRealmObjects.where().equalTo("id", id).findFirst();
log(obj.id);
}
Of course, if you are certain that objects with the ids exist, you can simplify it a bit:
String[] objectIds = new String[]{"1", "10", "2", "3"};
for (String id : objectIds) {
MyRealmObject obj = realm.where(MyRealmObject.class).equalTo("id", id).findFirst();
log(obj.id);
}