NullPointerException空指针错误:检查变量是否进行了初始化
形式一:错误代码:
footer.findViewById(R.id.load_layout).setVisibility(View.GONE);
解决方案:
private LinearLayout bottom;
bottom = footer.findViewById(R.id.load_layout);
//找到底部布局的控件,首先需要隐藏这个底部布局
bottom.setVisibility(View.GONE);
总结:如果报了NullPointerException空指针错误,可以将变量进行全局初始化,然后再进行使用
形式二:错误代码
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.mvp_demo.IPresenter.search()' on a null object reference
定义了一个IPresenter对象,但是没有为其赋值
private IPresenter mPresenter;
解决方案:
mPresenter = new Presenter(this); //其中Presenter继承了IPresenter
总结:定义了一个对象的时候,如果因为这个对象而报空指针错误,那么就是该对象没有初始化(没有为该对象进行赋值)