简体   繁体   中英

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.

So, I took the debugger and stepped through my onCreate method:

@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 . 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. 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. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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