2

我有一个与此讨论中描述的问题类似的问题:当底层数据库更改时,我需要刷新 ListView,但是查询很昂贵,所以我在 AsyncTask 中进行。

这是更新的光标准备好后我所做的。(这也是列表最初在启动时填充的方式。)

@Override
protected void onPostExecute(Cursor result) {
    if (activity != null) {
        if (currentCursor != null) {
            // existing cursor is closed by adapter.changeCursor() so
            // we don't need to explicitly close it here 
            stopManagingCursor(currentCursor);
        }
        currentCursor = result;
        startManagingCursor(currentCursor);

        if (adapter == null) {
            adapter = getAdapter(result);
            setListAdapter(adapter);
        } else {
            adapter.changeCursor(result);
        }

        activity.onGotList(result, dbAdapter);
    }
}

这是我得到的错误。它不会每次都发生,这更令人沮丧。

Releasing statement in a finalizer. Please ensure that you explicitly call close() on your cursor: SELECT DISTINCT   t._id AS _id,   t.amount,   t.date,   t.memo,   t.synced,   t.flag,   (children.pa
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
     at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:62)
     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:100)
     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:46)
     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:53)
     at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1412)
     at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1382)

所以,我显然没有正确关闭光标。如果我调用currentCursor.close()而不是依赖传出的 Cursor 被 关闭adapter.changeCursor(),那么我会收到关于关闭 Cursor 两次或关闭 Cursor 的警告null

这样做的正确方法是什么?

在我链接到的讨论中,Dianne Hackborn 建议使用 aLoader代替。这不是我的选择,因为我的代码必须在 Android 2.1 上运行。

4

3 回答 3

0

当 Activity 暂停或终止时,尝试 .close() 光标。在活动的 onPause() 或 onDestroy() 部分。

于 2011-11-14T21:38:03.533 回答
0

基本上,从两个不同的助手访问同一个数据库是可能的,但非常不好的做法,所以如果你有一个执行数据库查询的活动,你不应该也有一个线程访问它,否则 android 会在 logcat 中抛出一个安静的错误,然后忘记查询...

我发现的最佳解决方案是实现一个可运行线程池,每个线程池都是一个数据库查询,它们都使用相同的数据库助手。因此,任何时候只有一个线程在访问数据库,并且当线程池启动/停止时,数据库只是打开和关闭。

可以在此处找到线程池模式的实现:http: //mindtherobot.com/blog/159/android-guts-intro-to-loopers-and-handlers/

于 2011-11-14T21:51:02.763 回答
0

如果您没有更改任何其他内容,那么从列表中重新绘制是否有必要更改光标。你能摆脱只需要当前的适配器吗?

类似的东西

adapter.getCursor().requery();

虽然如果你在主 ui 线程以外的线程中,你可能想用它来调用它

//Did not realize this was deprecated Thanks to Graham Borland for the heads up
runOnUiThread(new Runnable(){
    public void run(){
        adapter.getCursor().requery();
    }
});

取决于你的设置。

新的解决方案仍然需要测试,并确保它不会引起问题,显然 startManaginCursor 和 stopManaginCursor 也已被弃用,所以这个解决方案也不值得。

stopManagingCursor(adapter.getCursor());
if (!adapter.getCursor().isClosed()) 
    adapter.getCursor().close();
//cursor creation stuff here if needed
startManagingCursor(newCursor);
adapter.changeCursor(newCursor);
于 2011-11-14T21:57:14.150 回答