robigroza
robigroza

Reputation: 589

Providing default string for color method

I need to set default value for this method, because I have crash when no data is forwarded to method, but method is called.

public int getTagColorFromColorStr(String colorStr) {
    int color = Color.WHITE;
    if (colorStr != null && colorStr.length() > 0) {
        String[] parts = colorStr.split(AppConstant.TAG_COLOR_STR_SEPEATOR);

        double red = Double.parseDouble(parts[0]) * 255;
        double green = Double.parseDouble(parts[1]) * 255;
        double blue = Double.parseDouble(parts[2]) * 255;
        double alpha = Double.parseDouble(parts[3]);

        // AppDebugLog.println("double color in getTagColorFromColorStr : "
        // + red + " : " + green + " : " + blue
        // + " : " + alpha);
        color = Color.rgb((int) red, (int) green, (int) blue);

    }

Stack trace of the crash says:

 11-18 14:45:57.767 28001-28001/com.mps.itickle E/AndroidRuntime: java.lang.NumberFormatException: Invalid double: "#FFFFFF"

Value that is provided to method when it works looks like this:

colorStr: "0.0,0.0,0.0,1.0"

Thanks on answers!

Upvotes: 1

Views: 92

Answers (2)

robigroza
robigroza

Reputation: 589

Fix here was to fix this line like this:

if (colorStr != null && colorStr.length() > 0 && !colorStr.contains("#"))

Issue here was that #FFFFFF value was used instead of String value "0.0,0.0,0.0,0.0", so

 String[] parts = colorStr.split(AppConstant.TAG_COLOR_STR_SEPEATOR);

tried to split #FFFFFF with commas, and that caused a crash.

Upvotes: 0

jollarvia
jollarvia

Reputation: 379

Color.White is the string value you default to: "#FFFFFF". This is the hex value and not what you need because there are no ints to convert. You have to convert it to rgb before you put it in color. Refer to this page for how to do that: convert-hex-to-rgb

Converting the alpha is straightforward after that. It's just repeating the same behavior for the remaining hex values.

For brevity's sake "FF" is hex for 255 so white is 255,255,255

Upvotes: 1

Related Questions