【问题标题】:how to close Cursor after ListView AdapterListView 适配器后如何关闭光标
【发布时间】:2017-05-19 23:46:02
【问题描述】:

我有这样的代码:

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 应该在哪里关闭?我是否需要为此编写特殊处理,还是在光标完成时自动关闭?

【问题讨论】:

    标签: android


    【解决方案1】:

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

    但为了避免Cursor 的问题,你应该NOTCursor 对象传递给Adapter,从Cursor 获取数据并关闭它,然后传递数据到Adapter

    【讨论】:

    • 看起来像是答案的候选者。我看到人们将数据从游标预取到数组中,但它看起来很尴尬(但可能非常适合我的情况,因为我在游标中没有很多记录)。您能否提供关于在 onPause() 中关闭游标的文档/帖子的任何参考?
    【解决方案2】:

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

    【讨论】:

    • 我猜是一样的,但你能提供任何规格参考来证明吗?
    • 似乎这是一个错误的答案,因为游标将不是由适配器关闭,而是由游标对象终结时的 GC 关闭。不建议这样做,因为会浪费与游标相关的资源。正确的答案是在onPause/onResume上关闭并重新创建光标,查看其他答案
    【解决方案3】:

    这里有一些我发现的关于这个主题的信息:有一个已弃用的方法 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

    【讨论】:

      【解决方案4】:

      调用 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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-11-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多