Reputation: 387
Earlier I got the integer value for a colour and converted it to Hexadecimal for storing in a database, now when i read it back and try to convert it back to an integer to use .setBackgroundColor(int)
i get the following error
java.lang.NumberFormatException: Invalid int: "ff0071dc"
on this line
items[i].setColourCode(Integer.parseInt(currentJourneys.get(i).getJourneyColourCode(), 16));
Also, if I hardcode in the hex value like this
colourLbl.setBackgroundColor(0xff0071dc);
it works fine
Am I doing something wrong? How else can i get the hex value out and use it to set the background colour?
Upvotes: 1
Views: 1706
Reputation: 272
I will recommend Color.parseString()
to do it.
Parse the color string, and return the corresponding color-int. If the string cannot be parsed, throws an IllegalArgumentException exception. Supported formats are: #RRGGBB #AARRGGBB or one of the following names: 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray', 'grey', 'lightgrey', 'darkgrey', 'aqua', 'fuchsia', 'lime', 'maroon', 'navy', 'olive', 'purple', 'silver', 'teal'.
http://developer.android.com/reference/android/graphics/Color.html#parseColor(java.lang.String)
Upvotes: 2
Reputation: 39873
You have two possibilities to convert a hex
representation to int.
By casting a parsed long to int
int color = (int) Long.parseLong(hex, 16);
or by using a BigInteger
to parse the value
int color = new BigInteger(hex, 16).intValue();
Some time in the future you might also be able to use the Java 8 method for parsing unsigned int values
int color = Integer.parseUnsignedInt(hex, 16);
Upvotes: 1