Android: do I need to close Cursor objects?

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;
}

是的,建议在完成使用该游标对象时关闭游标,以便游标可以执行关闭时想要执行的任何保留内容的工作。


Cursor is not a class but an interface. If your Cursor object is from a SQLite query, it is a SQLiteCursor. In that definition (Androidandroid-sdksourceandroiddatabasesqliteSQLiteCursor.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.


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

链接地址: http://www.djcxy.com/p/11324.html

上一篇: 如何手动发布/取消发布?

下一篇: Android:我需要关闭游标对象吗?