Aswin Aswin - 6 months ago 38
Android Question

What is The use of moveToFirst () in SQLite Cursors

I am a programming newbie
and I found this piece of code in the internet and it works fine

Cursor c=db.query(DataBase.TB_NAME, new String[] {DataBase.KEY_ROWID,DataBase.KEY_RATE}, DataBase.KEY_ROWID+"= 1", null, null, null, null);
if(c!=null)
{
c.moveToFirst();
}


but I am not able to understand the use of the

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


part. What does it do exactly , and if I remove the

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


part, the code doesn't work.

Answer

The docs for SQLiteDatabase.query() say that the query methods return:

"A Cursor object, which is positioned before the first entry."

Calling moveToFirst() does two things: it allows you to test whether the query returned an empty set (by testing the return value) and it moves the cursor to the first result (when the set is not empty). Note that to guard against an empty return set, the code you posted should be testing the return value (which it is not doing).

Unlike the call to moveToFirst(), the test for if(c!=null) is useless; query() will either return a Cursor object or it will throw an exception. It will never return null.

Comments