7

I am developing a restaurant menu app in Android. My app has one database table which has the following columns:

  • id (primary key)
  • category
  • item name

The category column shows the category of item such as veg, non veg, snacks etc. It has duplicate values and I want to select only distinct values from this column. I have tried the following but it is not working if anyone can provide a solution:

String query = "SELECT DISTINCT category FROM todo";

Cursor  cursor = database.rawQuery(query,null);
if (cursor != null) {
    cursor.moveToFirst();
}

return cursor; 
PeterJ
  • 3,705
  • 28
  • 51
  • 71
sagar
  • 1,900
  • 5
  • 30
  • 45
  • i am not getting any sqlite errors, but app stops running, debuger shows error source not found. Curently i am not using any logging in app – sagar Sep 13 '11 at 14:11
  • You should use logcat to debug your application. It will give us more information about your problem.. – Jeremy D Sep 13 '11 at 14:34

4 Answers4

12

You can also use this specific query-Method of the SQLiteDatabase class that takes a boolean value to determine whether you want distinct values or not:

public Cursor query (boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

Link to Android Reference

This way you don't have to use rawQuery at all.

Bashorings
  • 384
  • 3
  • 10
6

Try:

"SELECT DISTINCT category as _id, category FROM todo"

This worked for me in the same situation.

Aliaksei Kliuchnikau
  • 13,589
  • 4
  • 59
  • 72
StarSight
  • 69
  • 1
  • 2
1

This is how i make distinct, also to get categories

// Get Categories
public Cursor getCategories() {

    Cursor c = db.rawQuery("SELECT DISTINCT " + KEY_ITEM_CAT + " as " + KEY_ITEM_ID
            + ", " + KEY_ITEM_CAT + " FROM " + ITEMS_TABLE_NAME, null);

    if (c != null) {
        c.moveToFirst();
    }

    return c;
}
KiKo
  • 1,668
  • 7
  • 27
  • 56
0

I was searching for the same question, and I found something which is direct to the solution in the most simplest way! Check out this answer:

https://stackoverflow.com/a/13879436/4072073

Community
  • 1
  • 1
Tom R.
  • 71
  • 1
  • 1
  • 7