Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null objec

报错代码

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
        at com.race604.flyrefresh.sample.Activity.RecyclerViewExample$3.onClick(RecyclerViewExample.java:138)

解决办法
增加了一个ArrayList 动态数组作为中间数组
源码:

backlogList = new ArrayList();
        if (backlogListTemp != null) {
            ListIterator listIterator = backlogListTemp.listIterator();
            while (listIterator.hasNext()){
                backlogList.add((Backlog) listIterator.next());
            }
        }
        mAdapter = new RecyclerViewAdapter(this, backlogList);

问题描述:
1,这情况我遇到过;解决办法相同;
2,实验证明和实例化和赋初值无关;
3,最先报错是再适配器中的getItemCount(),也是空指针异常。

 java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
        at com.race604.flyrefresh.sample.adapter.RecyclerViewAdapter.getItemCount(RecyclerViewAdapter.java:147)

@Override
public int getItemCount() {
return mDataset.size();
}
尝试修改为if(mDataset ==null){return 0},能进入,但是添加item后崩溃。
求解:
1,为何要添加一个中间的ArrayList
2,RecycleView 和其他ListView的getView方法区别大吗(在getItemCount()方面)?

你可能感兴趣的:(android-studio)