android - 自动完成时疯狂的 SQLite 和光标泄漏

标签 android sqlite autocomplete adapter

在我的 Activity 中,我有一个 AutoCompleteTextView,它从我的自定义适配器获取其内容。我按照 this example 创建了我的适配器.

到目前为止,适配器可以正常工作,但我在泄漏和未最终确定的游标方面遇到了很多错误。我的问题是:如何在 runQueryOnBackgroundThread 中关闭数据库?

这是我的方法:

@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
    if (getFilterQueryProvider() != null) { 
        return getFilterQueryProvider().runQuery(constraint); 
    }

    StringBuilder buffer = null;
    String[] args = null;

    if (constraint != null) {
        buffer = new StringBuilder();
        buffer.append("UPPER (");
        buffer.append(DbUtilities.KEY_SEARCH_TERM);
        buffer.append(") GLOB ?");
        args = new String[] { "*" + constraint.toString().toUpperCase() + "*" };
    }

    final DbUtilities favsDB = new DbUtilities(context);
    return favsDB.getAllRecents(buffer == null ? null : buffer.toString(), args);
}

我试着修改成这样:

final DbUtilities favsDB = new DbUtilities(context);
Cursor c = favsDB.getAllRecents(buffer == null ? null : buffer.toString(), args);
favsDB.close();
return c;

但我遇到了 Invalid statement in fillWindow() 错误,并且 AutoCompleteTextView 不显示下拉列表。

这是我在类中设置适配器的方法,顺便说一句,它不扩展 Activity 而是扩展 RelativeView(因为我使用它来设置选项卡的内容):

AutoCompleteTextView searchTerm = (AutoCompleteTextView) findViewById(R.id.autocomp_search_what);

DbUtilities db = new DbUtilities(mActivity.getBaseContext());
Cursor c = db.getAllSearchTerms();
AutoCompleteCursorAdapter adapter = new AutoCompleteCursorAdapter(mActivity.getApplicationContext(), 
    R.layout.list_item_autocomplete_terms, c);
c.close();
searchTerm.setAdapter(adapter);

我无法使用 startManagingCursor(),所以我手动关闭了光标。但我仍然得到 Cursor not finalized 异常:

10-20 16:08:09.964: INFO/dalvikvm(23513): Uncaught exception thrown by finalizer (will be discarded):
10-20 16:08:09.974: INFO/dalvikvm(23513): Ljava/lang/IllegalStateException;: Finalizing cursor android.database.sqlite.SQLiteCursor@43d63338 on search_terms that has not been deactivated or closed
10-20 16:08:09.974: INFO/dalvikvm(23513):     at android.database.sqlite.SQLiteCursor.finalize(SQLiteCursor.java:596)
10-20 16:08:09.974: INFO/dalvikvm(23513):     at dalvik.system.NativeStart.run(Native Method)

关于如何解决这些错误的任何想法?谢谢!

最佳答案

首先,您关闭得太早了。当 AutoCompleteCursorAdapter 使用时,您不能关闭 Cursor。我也不确定在打开 Cursor 时是否可以安全地关闭数据库。

其次,我不知道您为什么说“不能使用 startManagingCursor()”,因为在您的情况下这似乎是一个很好的答案。

how do I close the db in runQueryOnBackgroundThread?

您可以在 onCreate() 中打开数据库并在 onDestroy() 中关闭它。

关于android - 自动完成时疯狂的 SQLite 和光标泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3976037/

相关文章:

java - AsyncTask 在另一个 Activity 中调用后返回 null

java - Android应用程序备份和恢复?

ios - Sqlite 遍历所有表

javascript - 如何使用 Electron 访问生产中的 sqlite3 数据库文件?

jquery - 垂直设置自动完成列表项

javascript - 使用 CodeMirror 自动完成

android - 配置 Android Studio 模块以使用 Google API

java - 相同的字符串不同

java - 如何播放广播直播流 .asx 视频/x-ms-asf?

javascript - ko jquery自动完成自定义绑定(bind)覆盖以前的绑定(bind)