Search code examples
javaandroidsqldatabaserealm

Sort In Realm with the length of string


in realm documentation, it is written to

result = result.sort("name", Sort.DESCENDING);

simple sort but i want to sort by shortest name First

normally in MySql we have

order by CHAR_LENGTH(Field)

is there any method like this in realm?


Solution

  • No, but you could easily have a redefined setter since 0.88.0 where you do the following:

    public class Word extends RealmObject {
        private String name;
    
        @Index
        @Required
        private long nameLength;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
            this.nameLength = name == null ? 0 : name.length();
        }
    }
    

    And you can specify a migration that would create this for pre-existing elements

    public class Migration implements RealmMigration {
        @Override
        public void migrate(final DynamicRealm realm, long oldVersion, long newVersion) {
            RealmSchema schema = realm.getSchema();
            if(oldVersion == 0) {
                RealmObjectSchema wordSchema = schema.get("Word");
                wordSchema.addField("nameLength", long.class, FieldAttribute.INDEXED, FieldAttribute.REQUIRED)
                          .transform(new RealmObjectSchema.Function() {
                              @Override
                              public void apply(DynamicRealmObject obj) {
                                  obj.set("nameLength", obj.getString("name").length());
                              }
                          });
                oldVersion++;
            }
        }
    
        @Override
        public void equals(Object object) {
            return object != null && object instanceof Migration;
        }
    
        @Override
        public int hashCode() {
            return Migration.class.hashCode();
        }
    }
    
    RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(context)
                                                 .schemaVersion(1)
                                                 .migration(new Migration())
                                                 .build();
    

    Then you can easily do

     realm.where(Word.class).findAllSorted(WordFields.NAME_LENGTH, Sort.ASCENDING, 
                                           WordFields.NAME, Sort.ASCENDING);