AutoComplete上疯狂的SQLite和游标泄漏

时间:2010-10-20 08:35:35

标签: android sqlite autocomplete adapter

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

到目前为止,适配器工作正常,但是我在泄漏和游标上遇到了很多未完成的错误。我的问题是:如何关闭runQueryOnBackgroundThread中的db?

这是我的方法:

@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没有最终确定的异常:

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)

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

1 个答案:

答案 0 :(得分:3)

首先,你太早结束了。在Cursor使用AutoCompleteCursorAdapter时,您无法关闭Cursor。我也不确定您是否可以在打开startManagingCursor()时安全地关闭数据库。

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

  

如何在runQueryOnBackgroundThread中关闭数据库?

您可以在onDestroy()中打开数据库,然后在{{1}}中将其关闭。

相关问题