android.content.Context.getSystemService(java.lang.String)' on a null object reference

今天使用View填充ViewPager时,遇到这个错误

Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

这是因为Context为空导致。

错误代码:

父类BasePager代码:


android.content.Context.getSystemService(java.lang.String)' on a null object reference
父类代码

子类implPager代码:


android.content.Context.getSystemService(java.lang.String)' on a null object reference
子类代码

在initView()方法中,用来inflate的activity为空,这是因为,initView是父类的方法由子类重写,会在子类构造方法之前调用,此时activity还未初始化,所以activity为null。

解决方法:

直接使用父类中的mActivity对View进行inflate。


android.content.Context.getSystemService(java.lang.String)' on a null object reference
更改后的子类代码

这里强调一下父类,子类中方法的调用顺序:

1.Class Son extends Father 时,若执行Son mSon = new Son();则会先调用父类Father的构造函数,再调用本身Son的构造函数;

2.如果Son和Father中都用相同的public static void Test()方法时,调用mSon.Test();不会调用父类的Test();没有static修饰时也不调用父类Test();因为并不是继承自父类,只是名字相同而已;若想在mSon.Test();中调用父类的Test()方法,可在mSon.Test();中写上super.Test(); 执行顺序是:父类构造方法-->子类构造方法-->mSon.Test();

3.如果Son中没有Test2()方法,而Father中有,则在执行mSon.Test2();时会直接调用父类Father的Test2();方法

4.父类中只要不是private修饰的变量,子类中都可以使用

5.子类重写父类的方法,该方法会在子类的构造方法之前调用。

第5点经过本人亲测。