Skip to content
Advertisement

Cursor should only select cells with a different value

I want, that my cursor is moving to the next cell with different content and I want the cursor to skip over all cells that have a value that already existed.

For example we have the column: Beer, Car, Car, House, Beer, Tree (in KEY_AREA)

The cursor should select: Beer, Car, House, Tree and skip 1 Car and 1 Beer.

        Cursor cursor = database.query(DBHelper.TABLE_AREA,
                columns,
                null,
                null,
                null,
                null,
                null,
                null);

        if (cursor.moveToFirst()) {
            do {
                Area_Names.add(cursor.getString(cursor.getColumnIndexOrThrow(DBHelper.KEY_AREA)));
            }
            while (cursor.moveToNext());

        } else
            Log.d("mLog", "0 rows");
        cursor.close();

Advertisement

Answer

Since you are interested only in the column DBHelper.KEY_AREA you can use the overload of query() which has as its first argument a boolean value indicating whether you want distinct results or not.

In your case you should pass true:

String[] columns = new String[] {DBHelper.KEY_AREA};
Cursor cursor = database.query(
    true,
    DBHelper.TABLE_AREA,
    columns,
    null,
    null,
    null,
    null,
    null,
    null
);

Also, you don’t need cursor.getColumnIndexOrThrow(DBHelper.KEY_AREA) to get the column’s index.
Your query returns only 1 column and you can safely use 0 as its index:

Area_Names.add(cursor.getString(0));
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement