简体   繁体   中英

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();

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM