Search in Realm. Sorted by fields
Another question about the kingdom.
I have this structure;
Class A has class B, which has a string name.
I want to sort a list of class A by B b which has the name "xy";
so this is how i tried but doesn't work.
realm.where(A.class).findAllSorted("b.name",true);
This indicates that there is no B.name field.
Any ideas how I can get it to work?
Thank.
source to share
The kingdom does not yet support sorting by reference. There is an open issue tracking this.
Below is a workaround for Realm's support for this feature:
class A extends RealmObject {
private B b;
// Storing the b.name as a field of A when calling setB(). But
// remember you cannot do it by adding logic to setB() since Realm's
// proxy will override the setters. You can add a static method to
// achieve that.
private String bName;
// getters and setters
// This needs to be called in a transaction.
public static void setBObj(A a, B b) {
a.setB(b);
a.setBName(b.getName);
}
}
And then you can sort the results using bName like:
realm.where(A.class).findAllSorted("bName",true);
source to share
I agree with @beeender, also you can use wrapper to do this in java style:
1.Define wrapper for A.class with
public class AWrapper {
public AWrapper(A a){
this.a = a;
}
private A a;
}
2. Convert the entire RealmObject to your wrapper. Something like that:
List<AWrapper> wrapped = new ArrayList<>();
for(A a : realmSet){
wrapped.add(new AWrapper(a))
}
-
Implement your own comparator to compare some field with A.class
private class OwnComparator implements Comparator<AWrapper>{ @Override int compare(AWrapper o1, AWrapper o2) { return o1.someField.compareTo(o2.someField) } }
-
Sorting using utils.Collections class
Collections.sort(wrapped, new OwnComparator())
source to share