v7 getSupportActionBar() 抛出 NullPointerException

v7 getSupportActionBar() is throwing NullPointerException

我正在从我的根 activity 启动一个新的 activity (TVMPDFActivity)。我正在使用 Android 注释,所以这就是我启动 Activity:

的方式
TVMPDFActivity_.intent(this.getActivity()).start();

TVMPDFActivityPDFPreviewActivity 的子类,PDFPreviewActivityActionBarActivity.

的子类

当我只是尝试获取 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?

您应该在 TVMPDFActivity 中的 setContentView 之前调用 super.onCreate,以便在尝试访问依赖于那个内部状态。对于 onCreate/onStart/onResume 调用 super 始终作为第一个语句