崩溃的ListView.removeFooterView(查看)ListView、removeFooterView

2023-09-06 02:11:41 作者:嘢岖尐灞仼

我收到的崩溃报​​告

 android.widget.ListView  lv;  lv.removeFooterView(v)

该错误是空指针异常。我检查的ListView本身是不为空。是什么原因造成的?是否有必要一定要移除的看法是不空?这就够了还是我第一次还需要检查页脚视图实际上已被添加?

The error is null pointer exception. I check that listView itself is not null. What causes this? Is it necessary to make sure the view to be removed is not null? Is that enough or do I first need to also check that the footer view actually has been added?

java.lang.NullPointerException
at android.widget.ListView.removeFooterView(ListView.java:374)

在我看来,这种方法应该是足够强大,不崩溃!为什么它不只是返回false,如果它不能去除的看法?

It seems to me this method should be robust enough not to crash! Why does it not just return false if it cannot remove the view?

PS。我想知道是否有人看到了这一点?

PS. I would like to know if anyone else has seen this?

推荐答案

不幸的是,你不提什么Android版本的错误报告的来源。然而,查看源$ C ​​$ C,Android 2.1系统,UPDATE1似乎是一个不错的选择。

Unfortunately you don't mention what Android version the error reports are coming from. However, looking at the source code, Android 2.1-update1 seems like a good candidate.

我就复制了整个方法把事情说清楚:

I'll just copy in the whole method to make things clear:

public boolean removeFooterView(View v) {
    if (mFooterViewInfos.size() > 0) {
        boolean result = false;
        if (((HeaderViewListAdapter) mAdapter).removeFooter(v)) { // <- line 274
            mDataSetObserver.onChanged();
            result = true;
        }
        removeFixedViewInfo(v, mFooterViewInfos);
        return result;
    }
    return false;
}

现在比较上面 removeFooterView(...)方法较新平台的实现:

Now compare above removeFooterView(...) method with the implementation of a more recent platform:

public boolean removeFooterView(View v) {
    if (mFooterViewInfos.size() > 0) {
        boolean result = false;
        if (mAdapter != null && ((HeaderViewListAdapter) mAdapter).removeFooter(v)) {
            if (mDataSetObserver != null) {
                mDataSetObserver.onChanged();
            }
            result = true;
        }
        removeFixedViewInfo(v, mFooterViewInfos);
        return result;
    }
    return false;
}

正如你所看到的,the've增加对某些成员不是一两个额外的检查。这将表明,第一种方法确实会就行274失败,如果 mAdapter == NULL ,而这不会导致崩溃与较新的实施。

As you can see, the've added in a couple of extra checks for certain members not being null. That would suggest that the first method will indeed fail on line 274 if mAdapter == null, whereas that wouldn't cause a crash with the newer implementation.

要解决它,你可能需要做的就是添加类似 lv.getAdapter()!= NULL 前试图删除页脚视图。

To work around it, all you probably need to do is add something like lv.getAdapter() != null before trying to remove the footer view.