Umair Sajid Minhas Umair Sajid Minhas - 11 months ago 99
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 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 Source

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... actionBar = getSupportActionBar();
if (actionBar != null) {
  actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorVelocity))); 


If you don't want to use the deprecated getResources().getColor() method, use this instead... actionBar = getSupportActionBar();
if (actionBar != null) {
  actionBar.setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, R.color.colorVelocity)));