I am currently learning android SQLite database programming. While reading this tutorial from here. I came across a section of code,
getContact()
// Getting single contact
public Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
My Questions
Question 1 If this code returns the query ,
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
Why do we move the cursor to the first row in this line ?
cursor.moveToFirst();
Question 2
What does this code do ?
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
I read the official documentation but still could not understand. Can some one explain with a simple example ?
Question 1: Because Cursor is set before first row element initially. Question 2: It gets Strings from row which is set as current in cursor object from columns (every row consists of columns) with numbers 0, 1 and 2. Then it uses them to create contact object.