Mucahit
Mucahit

Reputation: 573

how to query from realm database with distinct results java

I have got a Realm object class, and storing lots of data in there, imagine that I have a String uid; field. I want to get uid names, but on same uid names just only one time, For example

uid

AA

AA

BB

CC

DD

BB

BB

I want to get just AA,

BB,

CC,

DD.

Only one time. I looked over realm documentation but couldn't find anything.

Thanks for answers.

Upvotes: 11

Views: 15430

Answers (3)

karmstr7
karmstr7

Reputation: 225

The other answers are almost correct, but still incomplete.

The other solutions need to use .findAll() so that the return value remain RealmResult type.

RealmResult<Example> realmReault =realm.where(Example.class).distinct("uid").findAll();

On realm-gradle-plugin:6.0.2,

Upvotes: -1

Amol Suryawanshi
Amol Suryawanshi

Reputation: 2184

Please use below steps to work distinct on Realm

Update your realm version to realm :1.2.0 . because in older version distinct not working properly.

add @Index property to variable on which you want to apply distinct

execute your query like this

RealmResult<Example> realmReault =realm.where(Example.class).distinct("uid");

to include realm dependency in your project you can add below line in build.gradle(Project)

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.1'

        classpath "io.realm:realm-gradle-plugin:1.2.0"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

Above code is tested and working properly

Upvotes: 0

Kingston
Kingston

Reputation: 484

UPDATED :

You can use distinct() to get distinct entries for an object class.

// Returns the set of users that all have a different name
RealmResults<User> users = realm.where(User.class).distinct("name");

Note: .distinct will only work on fields that are indexed (@Index or @PrimaryKey). It doesn't work with child object property.

You can find more information about this method here in the official documentation. https://realm.io/docs/java/latest/api/io/realm/Realm.html#distinct-java.lang.Class-java.lang.String-][1]

Upvotes: 31

Related Questions