开发者

Cursor movement in Android

开发者 https://www.devze.com 2023-04-10 02:01 出处:网络
In Google\'s Notepad tutorial for Android (http://developer.android.com/resources/tutorials/notepad/notepad-ex1.html), they have the following for \"fetchNote\"

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开发者_Python百科.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 call mCursor.moveToFirst() will throw a NullPointerException. If the object isn't null and has been initialized properly, then you call moveToFirst() presumably to put the cursor at the beginning of the list of items.


When you first get a cursor, it's currently pointing to some sort of non-existing element before the first record. By calling moveToFirst the fetchNote method is prepping the cursor to be read immediately by the calling method. The reason we have to check if the cursor is null first is because there's a chance something could have gone wrong with the query and the database returned a null. If we tried to call moveToFirst on the cursor we'd get a null pointer exception.

0

精彩评论

暂无评论...
验证码 换一张
取 消