3

Another question about realm.

I have this structure;

Class A has a class B which has a String name.

I want to sort the list of Class A by B b that has a name "xy";

so this is how I tried but does not works.

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

This says that there is no field B.name.

Any ideas how could I make it works?

Thanks.

Ferenczi Jano
  • 89
  • 1
  • 1
  • 8
  • Realm doesn't support sort by link yet. There is an open issue tracking this https://github.com/realm/realm-java/issues/672 . – beeender Jul 16 '15 at 03:50

2 Answers2

5

Realm doesn't support sorting by link yet. There is an open issue tracking this .

Here is a workaround before Realm support that 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 by bName like: realm.where(A.class).findAllSorted("bName",true);

beeender
  • 3,555
  • 19
  • 32
1

I Agree with @beeender, also you can use wrapper to do it 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 all RealmObject in your wrapper. Somethink like this:

List<AWrapper> wrapped = new ArrayList<>();
for(A a : realmSet){
   wrapped.add(new AWrapper(a))
}
  1. Implement your own comparator to compare some field from A.class

    private class OwnComparator implements Comparator<AWrapper>{
       @Override
       int compare(AWrapper o1, AWrapper o2) {
           return o1.someField.compareTo(o2.someField)
       }
    }
    
  2. Sort using utils.Collections class

    Collections.sort(wrapped, new OwnComparator())

Vladyslav Sheruda
  • 1,856
  • 18
  • 26