2017-03-01 47 views
0

嗨所以我的項目在模擬器上啓動時出於某種原因有一個空指針,我不確定是什麼原因。這裏是我得到的錯誤:Android Studio中的空指針

W/System.err: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference 
W/System.err:  at com.panda.cleaner_batterysaver.ui.MainActivity.applyKitKatTranslucency(MainActivity.java:201) 
W/System.err:  at com.panda.cleaner_batterysaver.ui.MainActivity.onCreate(MainActivity.java:83) 

部分代碼:

private void applyKitKatTranslucency() { 

     // KitKat translucent navigation/status bar. 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { 
      setTranslucentStatus(true); 
      SystemBarTintManager mTintManager = new SystemBarTintManager(this); 
      mTintManager.setStatusBarTintEnabled(true); 
      mTintManager.setNavigationBarTintEnabled(true); 
      // mTintManager.setTintColor(0xF00099CC); 

      mTintManager.setTintDrawable(UIElementsHelper 
        .getGeneralActionBarBackground(this)); 

      getActionBar().setBackgroundDrawable(
        UIElementsHelper.getGeneralActionBarBackground(this)); 

     } 

    } 

繪製對象文件,其中的方法被稱爲:

public class UIElementsHelper { 

    private static final String NOW_PLAYING_COLOR = "NOW_PLAYING_COLOR"; 
    private static final String BLUE = "BLUE"; 
    private static final String RED = "RED"; 
    private static final String GREEN = "GREEN"; 
    private static final String ORANGE = "ORANGE"; 
    private static final String PURPLE = "PURPLE"; 
    private static final String MAGENTA = "MAGENTA"; 
    private static final String GRAY = "GRAY"; 
    private static final String WHITE = "WHITE"; 
    private static final String BLACK = "BLACK"; 

    /** 
    * Returns the ActionBar color based on the selected color theme (not used 
    * for the player). 
    */ 
    public static Drawable getGeneralActionBarBackground(Context context) { 
     final SharedPreferences settings = PreferenceManager 
       .getDefaultSharedPreferences(context); 

     Drawable drawable = new ColorDrawable(0xFF9acd32); 


     return drawable; 

    } 

} 
+0

getGeneralActionBarBackground方法的其餘部分發生了什麼? –

+0

更新了所有代碼 – Kenertj

+2

您是從Activity還是AppCompatActivity擴展?它是從AppCompatActivity嘗試使用getSupportActionBar。 – AndroidRuntimeException

回答

2

在默認styles.xml文件,檢查什麼正在使用的主題。如果你創建一個空活動的默認主題是:

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

然而,你可能使用了這樣的事情:

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

在這種情況下,你需要的onCreate手動設置操作欄這樣:

// Assuming you have a toolbar in your xml layout with id toolbar 
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 

setSupportActionBar(toolbar); 
ActionBar actionBar = getSupportActionBar(); 
if (actionBar != null) { 
    actionBar.setBackgroundDrawable(
       UIElementsHelper.getGeneralActionBarBackground(this)); 
} 

如果您不使用AppCompat,那麼您將需要使用getActionBar和適當的主題。