经过一段时间的 bug 搜寻后发现:
public class MainActivity extends BaseActivity { // BaseActivity extends Activity
public MainActivity() {
super();
getApplicationContext(); // NPE here
}
}
为什么?这在哪里记录?
冰冻
最佳答案
只是想了解一下发生了什么。 Activity extends ContextThemeWrapper它扩展了 ContextWrapper,Activity 从中继承了 getApplicationContext()
。 上下文包装器 implements it as :
@Override
public Context getApplicationContext() {
return mBase.getApplicationContext(); // mBase is a Context
}
only public constructor ContextWrapper
是:
public ContextWrapper(Context base) {
mBase = base;
}
在 ContextThemeWrapper
中 we have :
public ContextThemeWrapper() {
super(null);
}
并且由于 Activity 没有定义显式构造函数,所以在 Activity 的构造函数中调用了上面的构造函数 - mBase == null
- boom。
来自4.2.2_r1
的链接
关于android - 为什么 Activity 的构造函数中的 getApplicationContext() 会抛出空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16004891/