【问题标题】:Why would my fragment crash when reloading the loader?为什么我的片段在重新加载加载器时会崩溃?
【发布时间】:2013-06-04 00:12:21
【问题描述】:

虽然我无法复制此错误,但我仍然会收到一些与此错误相关的崩溃报告。我认为为我的列表适配器添加一个空检查可以解决它,但它仍然会发生。我错过了什么?

完整的堆栈跟踪: http://pastebin.com/Q6GwDU7Q

    public void onLoaderReset(Loader<Cursor> loader) {
    final int id = loader.getId();
    switch (id) {
    case LOADER_ID1:
        if (mAdapter != null)
            mAdapter.changeCursor(null); //Line 512 where stacktrace references
        break;
    case LOADER_ID2:
        //Other code here
        break;
    default:
        throw new InvalidParameterException("id=" + id);
    }
}

mAdapter 在 onActivityCreated 中初始化,但我意识到在键入此内容时我从未释放它,也许我应该在 onDetach 中执行该操作? mAdapter 附加到由 ListFragment 设置的 ListView。我将适配器光标设置为 null 以清除我拥有的列表。所以是的,我忽略了什么?

【问题讨论】:

  • 我无法想象它是您的 NPE 的来源,但我相信您应该使用 swapCursor 而不是 changeCursor,因为加载程序“拥有”光标并将关闭它。 swapCursor 不会关闭旧光标,而 changeCursor 会。
  • 我明白你的意思了,我看看能不能复制一下,然后试试你的解决方案。
  • 授予,问题 54142 (code.google.com/p/android/issues/detail?id=54142) 暗示了我认为会发生的事情
  • 嗯,这是一个非常讨厌的错误,我(我想大多数人)都不知道 :-)

标签: android android-fragments android-loadermanager


【解决方案1】:

在搜索了 Android 源代码之后,我现在看到就像 GreyBearedGeek 所说的那样,我应该让加载程序来处理光标破坏。

正如您在 CursorLoader 中看到的,如果传递一个新光标,它将处理关闭旧光标:

    /* Runs on the UI thread */
@Override
public void deliverResult(Cursor cursor) {
    if (isReset()) {
        // An async query came in while the loader is stopped
        if (cursor != null) {
            cursor.close();
        }
        return;
    }
    Cursor oldCursor = mCursor;
    mCursor = cursor;

    if (isStarted()) {
        super.deliverResult(cursor);
    }

    if (oldCursor != null && oldCursor != cursor && !oldCursor.isClosed()) {
        oldCursor.close();
    }
}

以及在重置时关闭光标。

    @Override
protected void onReset() {
    super.onReset();

    // Ensure the loader is stopped
    onStopLoading();

    if (mCursor != null && !mCursor.isClosed()) {
        mCursor.close();
    }
    mCursor = null;
}

所以我将来会使用 swapCursor 以免干扰 CursorLoaders 的处理,尽管我还没有看到这如何导致我在上面的堆栈跟踪中出现 NPE。

【讨论】:

    猜你喜欢
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 2014-04-04
    相关资源
    最近更新 更多