Java – Realm findAllSorted by field of a filed

Realm findAllSorted by field of a filed… here is a solution to the problem.

Realm findAllSorted by field of a filed

Another question about Realm.

I have this structure;

Class A has a Class B with a string name.

I want to sort the list of class A by B with the name “xy”;

So here’s what I tried but didn’t work.

realm.where(A.class).findAllSorted("b.name",true);

This indicates that there are no field B.name.

Any ideas to make it work?

Thank you.

Solution

Realm also doesn’t support sorting by link. There is a open issue tracking this.

This is a workaround before Realm supported the 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);
    }
}

You can then sort the results by bName, for example:

realm.where(A.class).findAllSorted("bName",true);

Related Problems and Solutions