简体   繁体   中英

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.

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).

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM