7

The following statement cursor.moveToNext() is always false. I expect the loop to execute once. I've tested that the query actually returns data.

Does anyone know what is the matter?

    String query ="SELECT(SELECT COUNT(*) FROM Table1) as count1, (SELECT COUNT(*) FROM Table2) as count2;";

    Cursor mCursor = mDb.rawQuery(query, null);

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

    while (cursor.moveToNext()) {   //<---------------return false here???
        String result_0=cursor.getString(0);
    }
4

2 回答 2

4

您可以通过这种方式迭代光标。

    if(moveCursor.moveToFirst()){
        do{
            //your code

        }while(moveCursor.moveToNext());
    }               
于 2013-03-07T04:34:43.070 回答
4

我知道你已经解决了你的问题,但这里是发生的事情的演练:

Cursor mCursor = mDb.rawQuery(query, null);

// At this point mCursor is positioned at just before the first record.

if (mCursor != null) {
    mCursor.moveToFirst();
    // mCursor is now pointing at the first (and only) record
}

while (mCursor.moveToNext()) {
    String result_0=cursor.getString(0);
}

// The loop above was skipped because `.moveToNext()` caused mCursor
// to move past the last record.

因此,在您只需要一条记录的情况下,您只需要mCursor.moveToFirst() OR您的mCursor.moveToNext().

于 2013-03-07T02:26:39.943 回答