Reputation: 1485
In my database adapter class, I have many methods like this:
public long getContactId(final String phoneNumber) throws SQLException {
final Cursor cur = mDb.rawQuery(
"select contact_id from contactphones where number=? limit 1;",
new String[] { phoneNumber });
return cur.moveToFirst() ? cur.getLong(0) : -1;
}
I appreciate the brevity of a method like that. But I am not calling Cursor.close(), and I'm not sure if that is a problem or not. Would the Cursor be closed and its resources freed in the Cursor.finalize()? Otherwise I would have to do:
public long getContactId(final String phoneNumber) throws SQLException {
final Cursor cur = mDb.rawQuery(
"select contact_id from contactphones where number=? limit 1;",
new String[] { phoneNumber });
final boolean retVal = cur.moveToFirst() ? cur.getLong(0) : -1;
cur.close();
return retVal;
}
Upvotes: 8
Views: 8407
Reputation: 2149
Yes, it's recommended to close the cursor when you are done using that cursor object so that cursor can do whatever house keeping work it wants to do upon closure.
Upvotes: 2
Reputation: 6326
Don't close the database. There is no need (data gets safely written to persistent storage at the earliest opportunity anyway). Open it once, on application startup, and reuse the same connection throughout your application's lifetime
Please refer this link
Upvotes: 0
Reputation: 1485
Cursor is not a class but an interface. If your Cursor object is from a SQLite query, it is a SQLiteCursor. In that definition (\Android\android-sdk\source\android\database\sqlite\SQLiteCursor.java)
, close()
is called in the finalize()
function. This may be different in other cursor types, since the Cursor interface does not specify this behavior.
Upvotes: 1