使用List的时候出现NullPointerException

当使用List的时候出现java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()'

我们应该这样判断:

1:List有没有初始化?没有初始化也会报这个错误

2:List中存放的是对象吗?如果是,首先判断List是否为null不能直接判断List.size();

如下的:List中存放的是对象:

if (result != null && result.getResult() == APIConfig.CODE_SUCCESS) {
        diaryList = result.getData().getContent();
        //diaryList 里面存放的是对象,如果为空的时候要判断diaryList=null的情况,不能直接判断diaryList.size()的大小
        if (diaryList != null && diaryList.size() != 0) {
            LinearLayoutManager growupManager = new LinearLayoutManager(context);
            growupManager.setOrientation(LinearLayoutManager.VERTICAL);
            growupRecycler.setLayoutManager(growupManager);
            //解决滑动不顺畅的问题
            growupRecycler.setHasFixedSize(true);
            growupRecycler.setNestedScrollingEnabled(false);
            //如果list是空的这里也会报错
            growupRecycler.setAdapter(new JourneyAdapter(diaryList));
        } else {
            growupRecycler.setVisibility(View.INVISIBLE);
        }
    } else {
        ToastUtil.toastByCode(result);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42618969/article/details/81434093