user2498079
user2498079

Reputation: 3012

Why call moveToFirst() after making query in database android

I am learning sqlite in android. Today I came across a code for finding specific entry in dateabase and returning it (for dispalying to user). I am little confused on what is happening in the code. First the programmer calls query method, then moves the cursor to first row.

Why has he called moveTofirst() method? Wouldn't this method place the cursor in the start of the database resulting in the lose of what the query method has returned.

Cursor c = database.query(TABLE_NAME,columns, NAME_COL+ "="+ findname, null,null,null,null);

if(c!=null)
{
   c.moveToFirst();
   name= c.getString(1);
   return name;
}

Regards.

Upvotes: 1

Views: 4481

Answers (4)

mithrop
mithrop

Reputation: 3353

When you make a query, you get back all the result, "encapsulated" in a Cursor object. This cursor contains all the rows you asked for, but not the entire database !!

For seeing the results, you have to move the Cursor through the rows it contains. Just after the query, the cursor doesn't point on anything. Calling moveToFirst() make the Cursor pointing the first row of the result of your query.

Also, as said in this answer of your question, you're also able to test if some results was actually returned.

Upvotes: 1

jkau
jkau

Reputation: 465

Another reason why you might want to call moveToFirst() is that when you first query, the cursor starts at index -1. Thus, you have to call moveToFirst() or any other moveTo.. function in order to access a proper row.

Upvotes: 2

Akash
Akash

Reputation: 631

No. Based on the docs the description of moveToFirst() is

Move the cursor to the first row.

So basically, you're setting the cursor to the first row of the results (and not the table itself) since the cursor contains only the rows matching your query and not all the rows from the table (unless you queried for them).

Upvotes: 3

Michael Shrestha
Michael Shrestha

Reputation: 2555

Calling moveToFirst() 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).

for more info at link

Upvotes: 1

Related Questions