Setting color from resource on Android


It is straight forward to set a color for text or background for example with the Android SDK but there is a mistake I made several times when getting started and this is what I want to cover in this short post.

Let’s take the example of setting the background color of a View and following the best practices, we want to use a color defined in colors.xml in the values directory of res.

The signature for the method used is setBackgroundColor(int color)

The mistake I made was to call it as myView.setBackgroundColor(R.colors.my_color) which does not trigger any warnings or errors at compile time nor at runtime but will give you grey no matter what color code you defined.

When thinking about it, it makes sense because R.colors.my_color returns the id value of the resource and not the actual color defined by the resource. So what we need to write instead is:
myView.setBackgroundColor(getResources().getColor(R.colors.my_color))

Note: if you are calling this outside of an Activity class or a class extending Activity, you need to specify the context for getResources so you may end-up with something like this:
myView.setBackgroundColor(context.getResources().getColor(R.colors.my_color))

Advertisements

WILT: NullPointerException when calling startActivity


That’s such a beginner error but I have no shame posting about it because I AM a beginner with Android  🙂

When trying to start a ListActivity from my main Activity, I kept on getting a NullPointerException. The code to launch my activity looked like this:

myActivityInstance.startActivity(new Intent(Intent.ACTION_VIEW));

Well, the problem was that I forgot to set the content view at the beginning of my launched activity. All I had to do was add this line at the beginning of my onCreate event handler:

setContentView(R.layout.tasks_list);