運到 等
運到 等

Reputation: 151

Android: SQLite, cursor.moveToNext() always returns false

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

Upvotes: 7

Views: 5803

Answers (2)

Harshid Vasoya
Harshid Vasoya

Reputation: 5721

you can iterate cursor this way.

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

        }while(moveCursor.moveToNext());
    }               

Upvotes: 4

Tass
Tass

Reputation: 1248

I know you've solved your problem, but here is a walkthrough of what happened:

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.

So, in your case of only needing a single record, you only need either mCursor.moveToFirst() OR your mCursor.moveToNext().

Upvotes: 4

Related Questions