Android 需要关闭游标、数据库,还是 none?

Android need close cursor, database, both or none?

几天来我一直在寻找解决我的 sqlite 和 android 问题的方法。我阅读了很多关于 sqlite 和 android 的文章。我看到有人说您需要关闭 CURSOR,其他人说您需要关闭 DATABASE,还有一些人说您需要关闭 BOTH,还有其他人说您不需要关闭 NOTHING,因为一个 Android 工程 post。

在我的应用程序中,我们对 sqlite 的使用太多了。

1 - 我们存储要同步的内容。 2 - 我们 add/delete 在幕后。 3 - 我们有 +/- 10 个由 Alarm Manager 启动的后台服务来同步一些东西。

一切运行在同一时间,多个线程等等。

当我获得该应用程序时,关闭 cursor/database 而同时打开其他光标时,我们遇到了很多很多崩溃。很多混乱。

所以,看完后,一个google工程师post(我不记得是什么google组),一个你不需要关闭sqlite游标或数据库的答案(我不记得了)我不知道是否有所作为)。

所以现在在我同步东西的后台服务中,我得到了关于它的错误:

Fatal Exception: android.database.CursorWindowAllocationException
Cursor window allocation of 2048 kb failed. # Open Cursors=593 (# cursors opened by this proc=593)

那我需要做什么?什么是正确的方法?有很多线程和使用它的 IntentService 会怎样?

我今天的示例代码:

public static MyInternalObject getFirstAudience() {
    SQLiteDatabase db = UbookProvider.getInstance().getReadableDatabase();
    String sql = "SELECT * FROM " + UbookContract.MyInternalObject.TABLE_NAME + " LIMIT 1";
    Cursor cursor = db.rawQuery(sql, null);

    if (cursor != null) {
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            do {
                return MyInternalObjectService.createFromCursor(cursor);
            } while (cursor.moveToNext());
        }
    }

    return null;
}

我在黑暗中,我不知道如何解决我在 android.

中的数据库问题

谁能帮帮我?

我的 github (github.com/prsolucoes) 也有很多开源项目。我为社区做了很多事情,但今天是我需要的。

是的,您需要关闭游标。一种方法是将所有查询包装在 try/finally 语句中。

Cursor c = null;
try {
    c = db.query(...)
} finally {
    if (c != null) {
        c.close();
    }
}

如果您正在使用 CursorLoaders(我强烈推荐),那么您不需要关闭游标,因为 Loader 框架会为您管理它。