Home > Blockchain >  why does setBackgroundDrawable() return null when passing an object but, works fine while using anon
why does setBackgroundDrawable() return null when passing an object but, works fine while using anon

Time:07-16

I want to change the color of ActionBar. I used this:

    ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor(" #070b2e"));
    getSupportActionBar().setBackgroundDrawable(colorDrawable);

It crashed the app and gave this warning:

Method invocation 'setBackgroundDrawable' may produce 'NullPointerException'

but when I write this instead,

     getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#070b2e")));

It works fine, App doesn't crash, color is changed now. however, warning still remains.

CodePudding user response:

Firstly that's not an anonymous class, that's simply using an object of ColorDrawable instead of storing it in an instance.

The warning says that getSupportActionBar() may be null so you need to add a null check for safety.

if(getSupportActionBar() != null) {
    ...your code..
}

CodePudding user response:

The crash on your first code seems caused by the space on " #070b2e" string - parseColor method doesn't do space trimming

  • Related