Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is The use of moveToFirst () in SQLite Cursors

Tags:

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.

like image 466
Aswin Avatar asked Sep 16 '12 06:09

Aswin


People also ask

What is cursor moveToFirst ()?

Cursor is an object that can iterate on the result rows of your query. Cursor can moves to each row. . moveToFirst() method move it to the first row of result table.

What is the use of cursor in SQLite?

Returns the numbers of rows in the cursor. Get the database that this cursor is associated with. This function is called every time the cursor is successfully scrolled to a new position, giving the subclass a chance to update any state it may have.

Which method is used to get data from cursor?

The get() methods return the data from the column in the row which can then be used by the app. The Cursor class contains the following methods for retrieving data from a row: byte[] Cursor. getBlob(int columnIndex): Returns the value as a byte[]

What is the use of cursor in Android SQLite?

A Cursor represents the result of a query and basically points to one row of the query result. This way Android can buffer the query results efficiently; as it does not have to load all data into memory. To get the number of elements of the resulting query use the getCount() method.


2 Answers

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.

like image 74
Ted Hopp Avatar answered Oct 20 '22 07:10

Ted Hopp


if (c.moveToFirst()) {   while(!c.isAfterLast()) { // If you use c.moveToNext() here, you will bypass the first row, which is WRONG     ...     c.moveToNext();   }  } 
like image 27
macio.Jun Avatar answered Oct 20 '22 08:10

macio.Jun