i'm trying to read a color from database sometimes it's a hex (#FFFFFF) and some times its a name (red,white) i want a way to convert these strings into a hex code
Asked
Active
Viewed 96 times
-2
-
3Update the data in the database to be uniform. – JakeB Sep 04 '19 at 08:05
-
@MorrisonChang it's not duplicate sir. He just want to check then get Color. – Ashish Sep 04 '19 at 08:15
-
@Ashish First answer from link is `public static int parseColor (String colorString)` which can take either hex value or a limited set of color string names like 'white','black' etc. Really @JakeB's answer is the correct one, but need feedback from OP. – Morrison Chang Sep 04 '19 at 08:18
-
check if the string match the hex format, else see @MorrisonChang link. Best solution is JakeB's comment – jhamon Sep 04 '19 at 08:20
-
@MorrisonChang i didn't check the answer i was reading the question only. Sorry – Ashish Sep 04 '19 at 08:21
-
@MorrisonChang i got (Unknown color error) from parseColor() method – Yahya Alborene Sep 04 '19 at 08:24
-
Without knowing what color you tried, it may not be supported by parseColor(). Likely database has HTML5 color names, but you'll have to check with owner of database. If you can't change database, you'll have to write/find conversion code. – Morrison Chang Sep 04 '19 at 08:28
1 Answers
0
Color.parseColor("#FFFFFF")
is what you need for hex values.
You cannot convert words into hex colors though. For such purposes you need to create mapping. It will look something like this:
String hexColor;
switch(colorName){
case "red": hexColor = Color.RED;
break;
case "white": hexColor = Color.WHITE;
break;
case "brown": hexColor = Color.parse("#654321")
break;
...
}
It is a kludge anyway and uniform mapping inside database should be done for the app support to be comfortable.
Hope it helps.

Pavlo Ostasha
- 14,527
- 11
- 35
-
-
It is yours database - you can scrap it and get all the colors with this names instead of hex and map all those colors like in example. Basically that is what I meant about comfortable support - each time new color will appear you will have to modify your app which is uncomfortable. You may create a migration though for the database - map all those colors to hex and replace them in the database with a query. – Pavlo Ostasha Sep 04 '19 at 08:35