2

I have two model object classes that are related to each other:

class Car {

    private String model;

    private Manufacturer manufacturer;

    // getter and setter methods

}

And:

class Manufacturer {

    private String name;

    // getter and setter methods

}

As you can see, the objects are related (each car has a manufacturer).

Now, in Realm, I need to get all cars, but sort them by their manufacturer's name. How can I sort by a relationship value?

Right now, all I have this:

RealmResults<Car> cars = realm.where(Car.class).findAll();

How can I sort this by the manufacturer's name, in ascending order?

2 Answers2

0

You probably noticed, but realm.where(Car.class).findAllSorted("manufacturer.name", Sort.ASCENDING) (link sort) is not yet supported in Realm 2.3.x.

In your case, the simplest way to go about it would be to leverage the benefits of Realm being a no-SQL database, and just store the manufacturer name next to the manufacturer itself.

class Car {

    private String model;

    private Manufacturer manufacturer;

    private String manufacturerName;

    public void setManufacturer(Manufacturer manufacturer) {
        if(manufacturer == null) { 
           this.manufacturerName = null; // direct field access works since 0.88.0
        } else {
           this.manufacturerName = manufacturer.getName();
        }
        this.manufacturer = manufacturer;
    }

}

And:

class Manufacturer {

    private String name;

    // getter and setter methods

}

Now you can do:

RealmResults<Car> cars = realm.where(Car.class)
                              .findAllSorted("manufacturerName", Sort.ASCENDING);
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • Not sure why, but it's not working. Even though I copied and pasted it exactly as is. –  Feb 05 '17 at 18:56
  • It appears that it's assigning `null` to all of the `manufacturerName`s. Not sure why. –  Feb 05 '17 at 19:46
  • that is only possible if the `manufacturer` you set is `null` or their `name` is null; but it's also possible if you're using Realm 0.87.5 or older. – EpicPandaForce Feb 05 '17 at 21:29
-1

You need something like as below,

   class MyComp implements Comparator<Manufacturer>
   {

    @Override
    public int compare(Manufacturer o1, Manufacturer o2) {
        // 
    // Compare the o1 properties with o2 properties
   }

}
DNAj
  • 240
  • 3
  • 9