0

I used the following code from this Q/A to change the background color of ActionBar:

public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    ActionBar bar = getActionBar();
    bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#000000")));
    setContentView(R.layout.activity_main);
}
//More codes here
}

I know that I should use getSupportActionBar() when using android.support.v7.app.ActionBarActivity. I don't use support v7. I am working in andoridx environment and I have imported the followings but I am not sure if these relating to the problem :

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference

Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82

2 Answers2

0

Use getSupportActionBar() instead of getActionBar()

after setContentView(R.layout.activity_main);

Rahul Gaur
  • 1,661
  • 1
  • 13
  • 29
0

I have solved the problem by setting up the environment as the following:

adding:

import static androidx.appcompat.app.AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR;

changing

extends Activity 

to

extends AppCompatActivity 

and shifting to support package by:

ActionBar bar = getSupportActionBar();
Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82