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

在我的数据库适配器类中,我有很多这样的方法:

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

我很欣赏这种方法的简洁性。 但是我没有调用Cursor.close(),我不确定这是否是一个问题。 游标将被关闭并且其游标在Cursor.finalize()中释放? 否则,我将不得不这样做:

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对象来自SQLite查询,则它是一个SQLiteCursor。 在该定义(Androidandroid-sdksourceandroiddatabasesqliteSQLiteCursor.java) ,在finalize()函数中调用close() 。 这在其他游标类型中可能会有所不同,因为Cursor接口不指定此行为。


不要关闭数据库。 没有必要(无论如何,数据会尽早写入永久存储器)。 在应用程序启动时打开一次,并在应用程序的整个生命周期中重复使用相同的连接

请参阅此链接

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

上一篇: Android: do I need to close Cursor objects?

下一篇: Best international alternative to Java's getClass().getResource()