In Google’s Notepad tutorial for Android (http://developer.android.com/resources/tutorials/notepad/notepad-ex1.html), they have the following for “fetchNote”
/**
* Return a Cursor positioned at the note that matches the given rowId
*
* @param rowId id of note to retrieve
* @return Cursor positioned to matching note, if found
* @throws SQLException if note could not be found/retrieved
*/
public Cursor fetchNote(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
Why do we move the cursor to first if it’s not null? I know it works, but I don’t understand it. Why not just return the cursor? Why isn’t it pointing to the object we want?
When you create the cursor object there is a slight chance that something could go wrong and the object wasn’t created and Null was returned by the
mDb.query()method. If this is the case then trying to callmCursor.moveToFirst()will throw aNullPointerException. If the object isn’t null and has been initialized properly, then you callmoveToFirst()presumably to put the cursor at the beginning of the list of items.