7

How do I execute "select distinct ename from emp" using GreenDao

I am trying to get distinct values of a column of sqlite DB using GreenDao. How do I do it? Any help appreciated.

Ananth
  • 1,065
  • 1
  • 12
  • 20

1 Answers1

16

You have to use a raw query for example like this:

private static final String SQL_DISTINCT_ENAME = "SELECT DISTINCT "+EmpDao.Properties.EName.columnName+" FROM "+EmpDao.TABLENAME;

public static List<String> listEName(DaoSession session) {
    ArrayList<String> result = new ArrayList<String>();
    Cursor c = session.getDatabase().rawQuery(SQL_DISTINCT_ENAME, null);
    try{
        if (c.moveToFirst()) {
            do {
                result.add(c.getString(0));
            } while (c.moveToNext());
        }
    } finally {
        c.close();
    }
    return result;
}

Of course you can add some filter-criteria to the query as well.

The static String SQL_DISTINCT_ENAME is used for performance, so that the query string doesn't have to be built every time.

EmpDao.Properties and EmpDao.TABLENAME is used to always have the exact column-names and table-names as they are generated by greendao.

AlexS
  • 5,295
  • 3
  • 38
  • 54
  • @oli edited this answer and noted, that this code needs to be synchronized because `Cursor` is not threadsafe. But since `Cursor c` is defined inside the method and not given to the outside world, this method is thread safe since every thread will have its own `Cursor`. Please do not reedit the synchronization topic, but instead leave a comment. P.S. IMHO the edit didn't follow [the rules](http://stackoverflow.com/help/privileges/edit) and shouldn't have been accepted, especially since this answer is accepted! – AlexS Feb 25 '16 at 10:38