1

I've been trying to set up buttons and other items with custom colours. I'm new to java, and I've been trying to learn how to use context properly. I have done some research, and I am still unable to find a solution.

The android monitor error is a null pointer exception, and this is the line of code it has a problem with.

int buttonBackground = ContextCompat.getColor(this, R.color.buttonBackgrounds);

I declared this variable within my class, and then further down in a method, I wrote this:

percussionButton.setBackgroundColor(buttonBackground);
instrumentButton.setBackgroundResource(android.R.drawable.btn_default);

I thought that these two might be conflicting, but that's about all I can think off.

I apologise if this has been answered before, I haven't been able to garner an answer from anything I have found so far.

things I've tried before:

int buttonBackground = ContextCompat.getColor(getBaseContext(), R.color.buttonBackgrounds);

int buttonBackground = ContextCompat.getColor(getApplicationContext(), R.color.buttonBackgrounds);
Mopork
  • 13
  • 3

1 Answers1

1

Read answers for understanding the difference between context getter methods here.
Maybe that causes the exception, you call getBaseContext(), when it returns null, hence the null pointer exception.
When want to use the context of an activity (inside the activity class), you can pass this (or YourActivityClass.this, where YourActivityClass consistently is the name of your activity) as the Context argument. So the line with the exception should be something like this:

int buttonBackground = ContextCompat.getColor(this, R.color.buttonBackgrounds);
Community
  • 1
  • 1
nvi9
  • 1,733
  • 2
  • 15
  • 20
  • Yes, I've tried that at it still has the same error. Thanks for the link, I'll try reading that to learn more. – Mopork Jan 27 '17 at 21:39
  • Wait, I've just read your question again, and noticed something: if you want to use the value of `buttonBackground` variable, you should set its value from the `onCreate` method of your activity, when the activity (with its stuff, context, etc) is set up. – nvi9 Jan 27 '17 at 21:48
  • Wonderful! it works now, thank you. I hadn't realized it was necessary to have it within the onCreate method. – Mopork Jan 27 '17 at 21:52
  • It can be called from other methods too, but just if the activity is created (on, or after `onCreate`) – nvi9 Jan 27 '17 at 21:55