how to query from realm database with distinct results java

佐手、 提交于 2020-01-03 07:17:12

问题


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.


回答1:


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]




回答2:


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



来源:https://stackoverflow.com/questions/30978857/how-to-query-from-realm-database-with-distinct-results-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!