Frank Cheng
Frank Cheng

Reputation: 6186

Is it necessary to check cursor is null before closing

I always write code like this:

Cursor c = getContentResolver().query(uri, 
        PHONE_LOOKUP_PROJECTION, null, null, null);

if (c != null) {
    if (c.moveToFirst()) { 
        bundle.contactId = c.getLong(LOOKUP_ID_COLUMN_INDEX);
        bundle.name = c.getString(LOOKUP_DISPLAY_NAME_COLUMN_INDEX);
    }


    c.close();
}

But i double if it is necessary to check the c is NULL or not. Because i feel like the value query returns always not null, even if it contains nothing.

Upvotes: 0

Views: 322

Answers (1)

Shubhayu
Shubhayu

Reputation: 13552

Believe me you MUST check it for null (I would have made the 'must' glow and jump around if i could), if you want to avoid cursor related crashes in the future, specially when you do requeries and data updates to your data source. You are doing it properly right now. Always check for null and always check the boolean returned by moveToFirst().

Upvotes: 2

Related Questions