我正在从我的根活动中启动一个新活动(TVMPDFActivity
)。我正在使用Android Annotations,所以这就是我启动Activity的方式:
TVMPDFActivity_.intent(this.getActivity()).start();
TVMPDFActivity
是PDFPreviewActivity
的子类,它是ActionBarActivity
的子类。
当我尝试获取ActionBar时,PDFPreviewActivity
中的onCreate抛出NullPointerException。在这一行:
final ActionBar actionBar = getSupportActionBar();
这是我的代码到NPE的堆栈跟踪:
Caused by: java.lang.NullPointerException
at android.support.v7.internal.app.WindowDecorActionBar.getDecorToolbar(WindowDecorActionBar.java:248)
at android.support.v7.internal.app.WindowDecorActionBar.init(WindowDecorActionBar.java:201)
at android.support.v7.internal.app.WindowDecorActionBar.<init>(WindowDecorActionBar.java:176)
at android.support.v7.app.ActionBarActivityDelegateBase.createSupportActionBar(ActionBarActivityDelegateBase.java:156)
at android.support.v7.app.ActionBarActivityDelegate.getSupportActionBar(ActionBarActivityDelegate.java:123)
at android.support.v7.app.ActionBarActivity.getSupportActionBar(ActionBarActivity.java:73)
at com.my.app.PDFPreviewActivity.onCreate(PDFPreviewActivity.java:63)
at com.my.app.TVMPDFActivity.onCreate(TVMPDFActivity.java:24)
at com.my.app.TVMPDFActivity_.onCreate(TVMPDFActivity_.java:31)
以下是涉及的各种类的onCreate方法:
public class TVMPDFActivity extends PDFPreviewActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
this.setContentView(R.layout.tvm_pdf_activity);
super.onCreate(savedInstanceState);
...
}
}
public abstract class PDFPreviewActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ActionBar actionBar = getSupportActionBar(); // throws NullPointerException
...
}
}
为什么我从支持v7代码深处获得NullPointerException?
答案 0 :(得分:1)
你应该在super.onCreate
setContentView
之前调用TVMPDFActivity
,以便让android有机会初始化其内部状态,然后再尝试访问依赖于该内部状态的内容。对于onCreate
/ onStart
/ onResume
,请将super
始终作为第一个声明