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.
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.
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.
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[]
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.
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
.
if (c.moveToFirst()) { while(!c.isAfterLast()) { // If you use c.moveToNext() here, you will bypass the first row, which is WRONG ... c.moveToNext(); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With