Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
    }
like image 500
運到 等 Avatar asked Mar 06 '13 23:03

運到 等


2 Answers

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

like image 167
Tass Avatar answered Sep 24 '22 21:09

Tass


you can iterate cursor this way.

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

        }while(moveCursor.moveToNext());
    }               
like image 22
Harshid Avatar answered Sep 25 '22 21:09

Harshid