这是我的代码:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
//android.support.v7.app.ActionBar actionBar = getSupportActionBar();
//actionBar.setTitle("Android");
ActionBar actionBar = getActionBar();
actionBar.setTitle("Droid");
}
在使用getSupportActionBar()时,我的应用程序与kitkat和其他新版本运行良好,但使用getActionBar导致错误.
这是错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.hide()' on a null object reference
at com.github.domain.geoquiz.QuizActivity.onCreate(QuizActivity.java:57)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372
为什么?来自android文档:
Caution: Be certain you import the ActionBar class (and related APIs)
from the appropriate package:If supporting API levels lower than 11:
import android.support.v7.app.ActionBarIf supporting only API level
11 and higher: import android.app.ActionBar
现在为什么这个应用程序崩溃了?
解决方法
如果您正在使用AppCompat,无论您的应用程序运行的是哪个Android版本,您都必须调用getSupportActionBar().
您定位的是哪个Android版本?
我建议你使用新的Toolbar而不是ActionBar,因为它的使用方式更灵活.