I’m trying to understand how cursors work and I don’t understand a portion of this code —
(lifted off of http://www.vogella.com/articles/AndroidSQLite/article.html)
public Comment createComment(String comment) {
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_COMMENT, comment);
long insertId = database.insert(MySQLiteHelper.TABLE_COMMENTS, null,
values);
Cursor cursor = database.query(MySQLiteHelper.TABLE_COMMENTS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
Comment newComment = cursorToComment(cursor);
cursor.close();
return newComment;
}
Can someone please explain what is going on here?
This is what I THINK is going on – He is inserting values into the table under the column named comment. He then does a query setting the cursor to where he added the comment in the table.
Then I am confused on why he does cursor.moveToFirst(). Isn’t the cursor pointing to the current comment he just added? I thought he is trying to return the comment he just inserted into the table, so couldn’t he just remove the moveToFirst() method?
Returns results are cursor object.
Make sure your are pointing to first element in the cursor object (or) cursor is not empty.
Calling another method to go through the cursor and perform what ever logic coded inside the method, which return
Commentobject.Close the cursor, so that it would be eligible GC and memeory will be free.
Return the comment object to caller.