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

The following cursor.moveToNext() statement is always false. I expect the loop to be executed once. I 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); } 
+6
source share
2 answers

I know that you solved your problem, but here is a step-by-step description 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, when you need only one entry, you only need mCursor.moveToFirst() OR your mCursor.moveToNext() .

+3
source

you can iterate over the cursor this way.

  if(moveCursor.moveToFirst()){ do{ //your code }while(moveCursor.moveToNext()); } 
+1
source

All Articles