为什么 Activity 构造函数中的 getApplicationContext() 会抛出空指针异常?

2024-03-05

经过一段时间的 bug 搜寻后发现:

public class MainActivity extends BaseActivity { // BaseActivity extends Activity

    public MainActivity() {
        super();
        getApplicationContext(); // NPE here
    }
}

为什么 ?这是在哪里记录的?
Froyo


只是为了感受一下正在发生的事情。Activity 扩展 ContextThemeWrapper http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/app/Activity.java?av=f#642这延伸了上下文包装器从谁Activity继承getApplicationContext(). 上下文包装器 将其实现为 http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/content/ContextWrapper.java#ContextWrapper.getApplicationContext%28%29 :

@Override
public Context  getApplicationContext() {
    return mBase.getApplicationContext(); // mBase is a Context
}

The 唯一的公共构造函数 http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/content/ContextWrapper.java#56 of ContextWrapper is :

 public  ContextWrapper(Context base) {
     mBase = base;
 } 

in ContextThemeWrapper we have http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.2.2_r1/android/view/ContextThemeWrapper.java#37 :

 public  ContextThemeWrapper() {
     super(null);
 }

自从Activity没有定义显式构造函数,上面的构造函数被调用 -mBase == null在 Activity 的构造函数中——boom。

Links from 4.2.2_r1

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 Activity 构造函数中的 getApplicationContext() 会抛出空指针异常? 的相关文章

随机推荐