deimos1988
deimos1988

Reputation: 6076

Accessing a database cursor and closing it

I have following code:

Cursor cursor = mDB.rawQuery(query, null);
                    cursor.moveToFirst();
                    do {
                        //do stuff
                    } while (cursor.moveToNext());
cursor.close();

query = "<some sql code>";
cursor = mDB.rawQuery(query, null);
  1. Can I close the cursor, and then open it again by making another query-call with .rawQuery?
  2. Is it ok to not check the cursor for null when doing cursor.moveToFirst()? As I understand it, the query can only return 0 results, which wouldn't be a problem when doing .moveToFirst?

Upvotes: 0

Views: 84

Answers (2)

ILovemyPoncho
ILovemyPoncho

Reputation: 2792

The documentation about close() says the you would not be able to use the cursor again:

Closes the Cursor, releasing all of its resources and making it completely invalid. Unlike deactivate() a call to requery() will not make the Cursor valid again.

If you are using the cursor in an adapter you can close the old cursor after you set the new one. swapCursor() returns the old Cursor, or returns null if there was not a cursor set, also returns null if the if you try to swap the same instance of the previously set cursor. Knowing that, you can try something like this:

Cursor c = adapter.swapCursor(cursor);

if(c != null)
    c.close();

Upvotes: 0

Gabe Sechan
Gabe Sechan

Reputation: 93728

You can do that, but it isn't doing what you seem to think it is. You aren't reopening the cursor. You're setting the variable to reference a new cursor for the new query.

I've seen null returns from db queries. I'd keep the null check. The amount of overhead is minimal.

Upvotes: 1

Related Questions