Umair Sajid Minhas Umair Sajid Minhas - 3 months ago 23
Java Question

How to Change action bar setBackgrounddrawable Color in Android Studio using R.Color in Java File?

I want to Change color of Action Bar using Java code in Android studio,

I have color.xml file for color codes

android.support.v7.app.ActionBar actionBar = getSupportActionBar();
actionBar.setBackgroundDrawable(new ColorDrawable(getColor(R.color.colorVelocity))); **//<<Error NullPointerException**


Tell me how to resolve this issue, as I want to use R.color I don't want to use color.parsecolor ("#hexcolor");

Answer

This is a null pointer exception issue. I'm not sure where you're calling the getSupportActionBar() from (that will give me a bit more context as to why) but you should always check for null when you call it. So change your code to...

android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
  actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorVelocity))); 
}

[EDIT]

If you don't want to use the deprecated getResources().getColor() method, use this instead...

android.support.v7.app.ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
  actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, R.color.colorVelocity)));
}