简体   繁体   English

为什么ListView.setAdapter(null)不引发空指针异常?

[英]Why doesn't ListView.setAdapter(null) throw a null pointer exception?

By chance I stumbled on this unique find. 我偶然发现了这个独特的发现。 My code broke because I was getting a NullPointerException on my Adapter after implementing a LoaderManager when I didn't have the exception previously. 我的代码坏了,因为实现了LoaderManager之后,当我之前没有异常时,在我的适配器上收到了NullPointerException异常。

So, I took the debugger and stepped through my onCreate method: 因此,我使用了调试器并逐步执行了onCreate方法:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    mDrawerListView = (ListView) inflater.inflate(
            R.layout.fragment_navigation_drawer, container, false);

    // Irrelevant code removed

    mDrawerListView.setAdapter(mAccountAdapter);
    return mDrawerListView;
}

The irrelevant code just include adding a footer view and setting onClickListeners but not once in this method (or any other) do I assign something to mAccountAdapter . 不相关的代码仅包括添加页脚视图和设置onClickListeners,但在此方法(或任何其他方法)中没有一次,我是否mAccountAdapter分配某些mAccountAdapter I know I'm supposed to, and I am going to, but I made the mistake of forgetting to do so. 我知道我应该做,而且我要去,但是我犯了忘记这样做的错误。

When I use the debugger and set a breakpoint at the setAdapter(mAccountAdapter) line I can see that mAccountAdapter is null. 当我使用调试器并在setAdapter(mAccountAdapter)行上设置断点时,我可以看到mAccountAdapter为空。 However, I can step over it and move on without ever getting a null pointer exception. 但是,我可以跨过它继续前进,而不会遇到空指针异常。 Why am I allowed to pass a null value into that function? 为什么允许将空值传递给该函数?

Why am I allowed to pass a null value into that function? 为什么允许将空值传递给该函数?

Why wouldn't you be? 你为什么不呢? After all, the ListView starts with a null adapter when you first create it. 毕竟,第一次创建ListView时,它会以一个null适配器开头。 If you look at the source for ListView and its ancestors, they have lots of checks for if mAdapter (the data member that will hold the now-current Adapter ) is null . 如果您查看ListView及其祖先的源代码 ,则它们会大量检查mAdapter (将保存当前Adapter的数据成员)是否为null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM