Ferenczi Jano
Ferenczi Jano

Reputation: 89

Realm findAllSorted by field of a filed

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.

Upvotes: 3

Views: 1890

Answers (2)

beeender
beeender

Reputation: 3565

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);

Upvotes: 5

Vladyslav Sheruda
Vladyslav Sheruda

Reputation: 1876

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())

Upvotes: 1

Related Questions