如何在ListView适配器后关闭Cursor

时间:2014-11-11 19:59:40

标签: android

我有这样的代码:

void showHistory(final long alertid) {
    final View view = getLayoutInflater().inflate(R.layout.dialog_history, null);
    ListView listView = (ListView) view.findViewById(R.id.list_history);
    final Cursor cursorHistory = helper.getHistory(alertid);
    CursorAdapter cursorAdapter = new HistoryAdapter(this,cursorHistory);
    listView.setAdapter(cursorAdapter);

    new AlertDialog.Builder(this)
            .setTitle("History")
            .setView(view)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                }
            })
            .show();
}

我的问题是 - cursorHistory应该关闭在哪里?我需要为此编写特殊处理,还是在光标定型的某个地方自动关闭?

4 个答案:

答案 0 :(得分:2)

您应该关闭onPause()中的光标并在onResume()中重新打开。

但为避免Cursor问题,您应Cursor对象传递给Adapter,从Cursor获取数据并关闭它,然后将数据传递给Adapter

答案 1 :(得分:0)

我认为您不必关闭光标。它将由适配器处理。

答案 2 :(得分:0)

这里有一些我在这个主题上找到的信息:有一个不推荐使用的方法 Activity.startManagingCursor(),它旨在关闭/重新查询光标 onPause()/ onResume(),正如@Abdullah的答案所示

不推荐使用 LoaderManager 类,它允许在后台线程中下载游标数据,而 startManagingCursor 适用于UI线程。

阅读本教程以获取更多信息:http://www.androiddesignpatterns.com/2012/07/loaders-and-loadermanager-background.html借用此处:https://stackoverflow.com/a/19652004/1028256

答案 3 :(得分:0)

调用changeCursor(null);在onPause()中。

来自文档:

void changeCursor (Cursor cursor)
Change the underlying cursor to a new cursor. If there is an existing cursor it will be closed.

Link to the changeCursor documentation

相关问题