質問

I'm using cursors to retrieve data from a database. I know how to retrieve entire columns to use on listviews and such, but I'm struggling to find a way to retrieve a single value.

Let's say I have a table with two columns ("_id" and "Name") and I have ten records (rows) in that table. How would I get, for example, the Name in the third row? Considering I defined a cursor that reads that table:

public Cursor getMyNameInfo() {

    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();


    String sqlTables = "MyNames";
    qb.setTables(sqlTables);
    Cursor c = qb.query(db, null, null, null,
            null, null, null);  

    c.moveToFirst();
    return c;
    }
役に立ちましたか?

解決

Instead of c.moveToFirst() use c.moveToPosition(2) (Cursor indexes are zero-based hence '2' is the third record).

Remember to check that the Cursor has valid data first though.

EDIT:

Once you've moved the cursor to the 3rd record as I explain above, use the following to just get the value of the "Name" column.

String theName = c.getString(getColumnIndex("Name"));

他のヒント

Cursor cursor = dbHelper.getdata();

        System.out.println("colo" + cursor.getColumnCount() + ""
                + cursor.getCount());

        cursor.moveToFirst();

        if (cursor != null) {

            while (cursor.isAfterLast() == false) {

                String chktitle = title.trim().toString();
                String str = cursor.getString(cursor.getColumnIndex("title"));

                System.out.println("title :: "
                        + cursor.getString(cursor.getColumnIndex("title")));
                System.out.println("date :: "
                        + cursor.getString(cursor.getColumnIndex("date")));
                System.out.println("desc :: "
                        + cursor.getString(cursor.getColumnIndex("desc")));

                if (chktitle.equals(str) == true) {
                    tvAddfavorite.setText("Remove Favorite");
                    break;
                }
                cursor.moveToNext();
            }
        }
        cursor.close();

Add a WHERE clause:

qb.appendWhere("_id = 2");

Thanks to the answers above I created the following method to give the value of an item from another column but in the same row.

public String getValueFromColumn(int position, String tableName, String columnToGetValueFrom) {

    SQLiteDatabase db = getReadableDatabase();
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    qb.setTables(tableName);
    Cursor c = qb.query(db, null, null, null,
            null, null, null);

    c.moveToPosition(position);
    String neededValue = c.getString(c.getColumnIndex(columnToGetValueFrom));
    return neededValue;
}

Hope it helps anyone.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top