Aprian
Aprian

Reputation: 1728

Cursor.moveToFirst() and nullpointerexception

My question is: Will moveToFirst() throw a NullPointerException?

Should I use:

if (cursor != null) {
    if (cursor.moveToFirst()) {
        // TODO
    }
}

or just:

if (cursor.moveToFirst()) {
    // TODO
}

Upvotes: 0

Views: 2995

Answers (2)

Sam
Sam

Reputation: 86948

It looks like you are using the Android Cursor and SQLiteDatabase classes. If so then cursor will never be null. (So you don't have to worry about a NullPointerException here.) They can be empty, but cursor.moveToFirst() will return false in this case. You are safe just using:

if (cursor.moveToFirst()) {
    // TODO
}

Or for more than one row:

while (cursor.moveToNext()) {
    // TODO
}

Upvotes: 4

Sieryuu
Sieryuu

Reputation: 1521

Calling cursor moveToFirst() will not error unless your cursor is null.

Upvotes: 3

Related Questions