Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Android Cursor.moveToNext() Documentation Correct?

Tags:

android

sqlite

boolean android.database.Cursor.moveToNext() documentation says:

http://developer.android.com/reference/android/database/Cursor.html#moveToNext%28%29

Move the cursor to the next row.

This method will return false if the cursor is already past the last entry in the result set.


However, my book says to do the following to extract data from a cursor:

Cursor myCursor = myDatabase.query(...);
if (myCursor.moveToFirst()) {
    do {
    int value = myCursor.getInt(VALUE_COL);
    // use value
    } while (myCursor.moveToNext());
}

Who's right? These both can't be true. If you can't see the contradiction, imagine myCursor has 1 row returned from the query. The first call to getInt() will work, but then moveToNext() will return true because it is not "already" past the last entry in the result set. So now the cursor will be past the last entry and the second call to getInt() will do something undefined.

I suspect the documentation is wrong and should instead read:

This method will return false if the cursor is "already at" the last entry in the result set.

Must the cursor be already PAST (not AT) the last entry before the moveToNext() method returns false?

No Snark Please

like image 433
user405821 Avatar asked May 12 '11 23:05

user405821


People also ask

How does cursor work in Android?

Introduction to Cursor in Android The basic purpose of a cursor is to point to a single row of the result fetched by the query. We load the row pointed by the cursor object. By using cursor we can save lot of ram and memory. Here, we pass the table name, column name only then we receive the cursor.

What does the startManagingCursor () function do?

startManagingCursor does not retain the Cursor's state across configuration changes. Instead, each time the Activity is destroyed due to a configuration change (a simple orientation change, for example), the Cursor is destroyed and must be requeried.

What is the cursor moveToFirst in Android?

moveToFirst() method moves the cursor to the first row.


1 Answers

A simpler idiom is:

Cursor cursor = db.query(...);
while (cursor.moveToNext()) {
    // use cursor
}

This works because the initial cursor position is -1, see the Cursor.getPosition() docs.

You can also find usages of cursors in the Android source code itself with this Google Code Search query. Cursor semantics are the same in SQLite database and content providers.

References: this question.

like image 91
orip Avatar answered Oct 01 '22 01:10

orip