Error parsing Colors from String
Asked Answered
R

4

8

EDIT:A Pastebin consisting of the relevant parts of my project:

Here is the updated code

Also ColouredItem is a wrapper for:

     public class ColouredItem
     {//Only a wrapper class,no behaviour has been defined here
        String name,colour;
     }

I get a NumberFormatException when trying to parse a colour from a String using the following code:

     row.setBackgroundColor(Color.parseColor(item.colour));

I use the following to create a list of items from a resource:

    for(int i=0;i<list.length;i++)
    {
        item=new ColouredMenuItem();
        String[] cmenu =list[i].split("#");
        item.name=cmenu[0];
        item.colour="#"+cmenu[1];
        Log.d(TAG, item.colour);
        menuList.add(item);
    }

This is the exception that I get...I have found that view.setBackgroundColor only takes an integer value:

         #ffffff 
         #ffffBB 
         #fff45f 
         #ffff00 
         Shutting down VM
         threadid=1: thread exiting with uncaught exception (group=0x4001d800)
         FATAL EXCEPTION: main
             java.lang.NumberFormatException: ffffff 
         at java.lang.Long.parse(Long.java:364)
         at java.lang.Long.parseLong(Long.java:354)
         at android.graphics.Color.parseColor(Color.java:207)
         at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)
         at android.widget.AbsListView.obtainView(AbsListView.java:1315)
         at android.widget.ListView.makeAndAddView(ListView.java:1727)
         at android.widget.ListView.fillDown(ListView.java:652)
         at android.widget.ListView.fillFromTop(ListView.java:709)
         at android.widget.ListView.layoutChildren(ListView.java:1580)
         at android.widget.AbsListView.onLayout(AbsListView.java:1147)
         at android.view.View.layout(View.java:7035)
         at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
         at android.view.View.layout(View.java:7035)
         at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1249)
         at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1125)
         at android.widget.LinearLayout.onLayout(LinearLayout.java:1042)
         at android.view.View.layout(View.java:7035)
         at android.widget.FrameLayout.onLayout(FrameLayout.java:333)
         at android.view.View.layout(View.java:7035)
         at android.view.ViewRoot.performTraversals(ViewRoot.java:1045)
         at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
         at android.os.Handler.dispatchMessage(Handler.java:99)
         at android.os.Looper.loop(Looper.java:123)
         at android.app.ActivityThread.main(ActivityThread.java:4627)
         at java.lang.reflect.Method.invokeNative(Native Method)
         at java.lang.reflect.Method.invoke(Method.java:521)
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
         at dalvik.system.NativeStart.main(Native Method)

Adding the # as some of the answers suggest did not solve the issue:

          java.lang.NumberFormatException: Invalid long: "#ffffff"
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
      at android.app.ActivityThread.access$600(ActivityThread.java:141)
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
      at android.os.Handler.dispatchMessage(Handler.java:99)
      at android.os.Looper.loop(Looper.java:137)
      at android.app.ActivityThread.main(ActivityThread.java:5103)
      at java.lang.reflect.Method.invokeNative(Native Method)

No difference with this implementation either:

          String cmenu=list[i];
          item.name=cmenu.substring(0, cmenu.indexOf("#"));
          item.colour=cmenu.substring(cmenu.indexOf("#"));
Rockey answered 23/10, 2013 at 13:7 Comment(7)
android provided a sophisticated method to parse color from string Color.parseColor("#ffffff"), did you try it;Hamford
I have indeed used int Color.parseColor(string)Rockey
what is the use of this "item.colour="#"+cmenu[1];" when you can use item.colour=list[i];Hamford
I need to extract a colour from a larger string,actually list[i] returns a lot of words #ffffff.Rockey
can you show us ColouredMenuItem.java file?Hamford
Just posted my answer could you please check it.Hamford
Hey,I have posted my complete code at the top as an edit inn a pastebin,I think I am doing something fundamental wrong.Rockey
A
12

Use this code

row.setBackgroundColor(Color.parseColor("#424242"));

it helped me too,dont remove "#".

i used this code

private List<String> item;

item = new ArrayList<String>();
item.add("#424242");
row.setBackgroundColor(Color.parseColor(item.get(0)));

and its working gud for me,may be your split thing is not working good

or for your code

Button btn;
ColouredMenuItem item;
ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
String[] list = new String[] { "Page1 #ffffff", "Page2 #ffffBB" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);

    setContentView(R.layout.sample);

    try {
        btn = (Button) findViewById(R.id.button1);
        for (int i = 0; i < list.length; i++) {
            item = new ColouredMenuItem();
            String[] cmenu = list[i].split("#");
            item.name = cmenu[0];
            item.color = "#" + cmenu[1];
            Log.d("colored", item.color);
            menuList.add(item);
        }



        btn.setBackgroundColor(Color.parseColor(menuList.get(1).color));
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

this is working good at my side

this is new code

Make your colored item as a bean class with getter and setter like this

public class ColouredMenuItem {// Only a wrapper class,no behaviour has been defined
                        // here
String name, colour;

List<ColouredMenuItem> list=new ArrayList<ColouredMenuItem>();

public List<ColouredMenuItem> getList() {
    return list;
}

public void setList(List<ColouredMenuItem> menuList) {
    this.list = menuList;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getColour() {
    return colour;
}

public void setColour(String colour) {
    this.colour = colour;
}

}

Then in your adapter use this code

try {
        Log.d(TAG, menuList.get(position).colour);
        textView.setText(menuList.get(position).getName());

        {
            row.setBackgroundColor(Color.parseColor(menuList.get(position).getColour()));
        }
    } catch (Exception ex) {
        Log.e(TAG, "Still does not work");
    }

Just give it a try,it works here at my side

Also your array is like this only na

<string-array name="menu_array">
    <item>Page1 #ff7788</item>
    <item>Page1 #ff6688</item>
    <item>Page1 #424242</item>
</string-array>
Acherman answered 23/10, 2013 at 13:23 Comment(9)
if you are using "#" with this,then print the value of item.colourAcherman
The first four lines of the logcat that looked a little dimmed out actually do that. String[] cmenu =list[i].split("#"); item.name=cmenu[0]; item.colour="#"+cmenu[1];Rockey
try with a hardcode value like mine first,if it wokrs then there may be a problem in your split.Acherman
worked with a harcoded value,worked but it does not work even upon adding the #.Rockey
Are you using try-catch so that you can catch the NumberFormatExceptionRockey
no i didnt got Numberformat exception....but its a good practise to use try catch...just give it a tryAcherman
check the updated code,is there somethinh wrong with MyAdapter,or is it that I cannot use Color.parseColor there.It works well with hardCoded string but there seem to be issues when I pass it using position.Check edit at top of post...Rockey
ok i got your problem..i have done it like your and pasting new code hereAcherman
I changed the array from <string-array><item><name>Page 1</name><colour>#ffff45</colour></item>...</string-array>.It was strange how Android did not object to this array(is it documented).It gave the output value,it seemed as Page 1 #ffff45,thus making it practically useless.Rockey
C
0

Try Color.parseColor("#ffffff"); instead of Color.parseColor("ffffff");

Chondroma answered 23/10, 2013 at 13:14 Comment(6)
To get the color value I took something like name color and split it at #: item.name=cmenu[0]; item.colour="#"+cmenu[1]; The first four lines of the logcat represents the string value for colour obtained after parsingRockey
Because the String looks like Page 1 #ffffffRockey
you must add a "#" before the color hex. like "ffffff" must be "#ffffff". otherwise it wont work.Chondroma
I have posted the results of adding #.I think I am doing something simple wrong.I have posted the entire code in a pastebin...edit at top of post.Rockey
Yes,they do in the pastebin I have pasted a logcat where the String #ffff45 returns a value of -187 when passed to Color.parseColorRockey
the integer value doesn't matter. just try to set the colorChondroma
S
0

look at the Stack trace it will tell you:

 java.lang.NumberFormatException: ffffff  
     at java.lang.Long.parse(Long.java:364)
     at java.lang.Long.parseLong(Long.java:354)
     at android.graphics.Color.parseColor(Color.java:207)
     at com.example.samplelistproject.MadAdapter.getView(MadAdapter.java:60)

Line by Line:

you are trying to format Hexadecimal (base 16) value "0xffffff" to a decimal (base 10) value
you're trying to parse hexadecimal string "ffffff" to type Long
same as above.
error is thrown when calling `Color.parseColor()`
error is thrown from your MadAdapter.java Class on line 60.

so, you need to find a way to parse it from Hexadecimal instead of decimal value. Hexadecimal values are usually preceeded by 0x[value] OR #[value]

Selfgoverned answered 23/10, 2013 at 13:16 Comment(0)
H
0

Assuming: while parsing the color from string object "item" is not taken from array of list, rather its taking instance variable of ColoureMenuItem.

    ColouredMenuItem item;
        ArrayList<ColouredMenuItem> menuList = new ArrayList<ColouredMenuItem>();
        String[] list = new String[]{"#ffffff","#00ffff"};





// parsing your string here, no change in this
for(int i=0;i<list.length;i++)
            {
                item=new ColouredMenuItem();
                String[] cmenu =list[i].split("#");
                item.name=cmenu[0];
                item.color="#"+cmenu[1];
                Log.d("colored", item.color);
                menuList.add(item);
            }

// confirming whether value are parsing or not.

            for(int i=0;i<menuList.size();i++)
            {
                int color = Color.parseColor(menuList.get(i).color);
                Log.d("color",""+menuList.get(i).color);
            }

and your ColouredMenuItem class.

public class ColouredMenuItem {

    public String color;
    public String name;

}
Hamford answered 23/10, 2013 at 13:50 Comment(1)
Think of it like String[] list= {"Page1 #ffffff","Page2 #ffffBB"}; instead of the the variable you have.It works with a hardcoded string but it does not seem to be working here.Rockey

© 2022 - 2024 — McMap. All rights reserved.