24

I'm getting the above error when I try to run the following code:

int colourInt = Color.parseColor(colour.getHexValue());

The offending hexadecimal value is ee3090b0. Is there a way I can convert a colour hexdecimal value to its integer equivalent and still retain the alpha value? I've tried following a suggestion made in this post, but it isn't working...

Community
  • 1
  • 1
Anna Lam
  • 777
  • 2
  • 11
  • 28

4 Answers4

63

From documentation:

public static int parseColor (String colorString)

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 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray'

Your method probably returns a string that doesn't start with a #.

Vito Gentile
  • 13,336
  • 9
  • 61
  • 96
  • 5
    this may occurred, if containing space or newline in your color code string. so just trim the colorcode string. eg:- colorcode.trim(); – jaleel Nov 22 '13 at 05:54
  • it wants a 6 character long string. I think it throws an exception on 8 characters (or anything other than 6) – msecilmis May 10 '17 at 12:10
1

Wrap it inside a try catch block, and set in the catch block the default color to handle the exception. Make sure this color is right typed, also you can throw an exception to handle the failure.

For example, I'm parsing a color from Firebase remote config, if the fetch of that color throws an IllegalArgumentException I set the color to be the default in my app.

          try{
               color = Color.parseColor(RemoteConfigSingleton.getInstance().getEventColor());
            }catch (IllegalArgumentException e){
                color = Color.parseColor("#E53935");
            }

Doing this I avoid the fatal crash of the app

Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77
0

I want to add something with the accepted answer. I had similar exception while I'm trying to use black color using Color.parseColor("#000") which start with #.So the thing is inside your parseColor method it only accept a six digit hex code of color,If it is less or greater than this its give the exception.I change it like #121212(black) this and it works for me.

Saddan
  • 1,546
  • 16
  • 19
0

Use Color Like this there is some issue while parsing your color code you should use the color that is starting from '#' code Color.parseColor("#171C26")