android标题栏空指针异常

时间:2015-07-20 19:24:34

标签: android nullpointerexception android-titlebar

我知道这很简单,但我无法修复它。从SOF.com尝试了许多解决方案但没有成功。我试图显示活动的标题并抛出NPE。使用API​​19进行测试。下面是代码:

在活动中:

 public class DisplayImageActivity extends RootActivity {  
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        getActionBar().setTitle("Image Preview");

在清单中:

  <application
    android:allowBackup="true"
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

  <activity
        android:name=".DisplayImageActivity"
        android:label="<  app name  >"
        android:screenOrientation="portrait" >
    </activity>

在style.xml中:

   <style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

最后,logcat说:

    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.kittu.<> /com.example.kittu.<>.DisplayImageActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2334)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2392)
        at android.app.ActivityThread.access$900(ActivityThread.java:169)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1280)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:146)
        at android.app.ActivityThread.main(ActivityThread.java:5487)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at com.example.kittu.<  >.DisplayImageActivity.onCreate(DisplayImageActivity.java:44)
        at android.app.Activity.performCreate(Activity.java:5451)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)

2 个答案:

答案 0 :(得分:1)

我认为你正在使用AppCompat,那么你应该使用getSupportActionBar()代替getActionBar()

改变这个:

getActionBar().setTitle("Image Preview");

到此:

getSupportActionBar().setTitle("Image Preview");

希望这会有所帮助:)

答案 1 :(得分:1)

如果您使用的是支持库,则您的活动需要扩展它

import android.support.v7.app.AppCompatActivity

public class MainActivity extends AppCompatActivity{

并使用getSupportActionBar()代替getActionBar()