2

I am storing things in a sqlite database. One of its attributes is a color. When I display this, I want to do

objLinearLayout.setBackgroundColor(some_int)

Normally I'd use R.color.red in place of some_int. However, I am persisting the color, and I think the R file generates a new id for red each time I run the app, making that method not feasible. I could store the string representation, like "red", and in my java code check for the color string and apply the correct R.color, but that looks ugly. Is there a way around that?

HukeLau_DABA
  • 2,384
  • 6
  • 33
  • 51
  • What about the hex and using some other function to convert to whatever other format you need? – Phix Oct 30 '14 at 00:24

3 Answers3

5

You should not be storing the values from R (i.e. R.color.red) in any kind of permanent storage. The value is regenerated on every app build, so if an update is put out what used to be R.color.red is now R.color.purple or worse R.layout.activity_main.

What you could do is store the resolved color in the SQLite database (getResources().getColor(R.color.red)) since that is just a integer representing a color, not a pointer to a color. That way if you eventually change R.color.red from #F00 to #E00, the value saved will be #F00.

dandc87
  • 1,096
  • 5
  • 7
4

You could store hex codes and use it when you set colors. Like ll.setBackgroundColor(Color.parseColor("#ffffff"));

Here's some good explanation on the comments of another question.

Changing Color with LinearLayout and TextView in Java (Android)

Community
  • 1
  • 1
0

If you want to save the name of the color in your DB, you can use getIdentifier method.

For example:

Resources resources = getResources();
int colorId = resources.getIdentifier("your_color_name", "color", getPackageName()); 
SuperFrog
  • 7,631
  • 9
  • 51
  • 81