Payal
Payal

Reputation: 913

Android Xml Parsing issue

I am trying to parse xml and put its value in two arraylist .but i am getting array index out of bound exception on bold line

My xml looks like this :-

<visitor_info>
<txt_trailer_no_front>23,5</txt_trailer_no_front>
<txt_trailor_no>24,4</txt_trailor_no>
<txt_trailer_no_bol>25,</txt_trailer_no_bol>
</visitor_info>

and my code to parse it is:

for(Node n = doc.getFirstChild().getFirstChild().getNextSibling(); n!=null; n = n.getNextSibling().getNextSibling())
    {
        String str=getElementValue(n);

        if(n.getNextSibling()==null)
        {
            Log.i("info",str+"test");
            fillid.add(str.split(",")[0]);
            **fillvalues.add(str.split(",")[1]);**//Exception occurs
            break;
        }


        if(!str.equals("") && !str.equals(null))
        {
        fillid.add(str.split(",")[0]);
        fillvalues.add(str.split(",")[1]!=null?str.split(",")[1]:"");
        }
    }
    Log.i("info",fillvalues.size()+"v");
    for(int i=0 ;i<fillvalues.size();i++)
    {
        Log.i("info","1");
        for(int j=0;j<values.size();j++)
        {
            Log.i("info","2");
            if(values.get(j).equals(fillid.get(i)))
            {
                Log.i("info","3");
                values.get(j).value=fillvalues.get(i);
                break;
            }
        }
    }


}

Upvotes: 0

Views: 54

Answers (2)

Hardik Joshi
Hardik Joshi

Reputation: 9507

You got array index out of bound exception here :

<txt_trailer_no_bol>25,</txt_trailer_no_bol>

Reason :

Your str contains only one element if you split it using str.split(","). So str.split(",")[1] is null.

You can use following way :

if(n.getNextSibling()==null)
            {
                Log.i("info",str+"test");

                String[] strarray=str.split(",");
                for(int i=0;i<strarray.length;i++){
                     fillid.add(str.split(",")[i]);
                }
                break;
            }

Upvotes: 1

Biraj Zalavadia
Biraj Zalavadia

Reputation: 28484

Try this way

for(Node n = doc.getFirstChild().getFirstChild().getNextSibling(); n!=null; n = n.getNextSibling().getNextSibling())
        {
            String str=getElementValue(n);

            if(n.getNextSibling()==null)
            {
                Log.i("info",str+"test");
                try {
                    fillid.add(str.split(",")[0]);
                } catch (Exception e) {
                    fillid.add("");
                }
                try {
                    fillvalues.add(str.split(",")[1]);
                } catch (Exception e) {
                    fillvalues.add("");
                }

                break;
            }


            if(!str.equals("") && !str.equals(null))
            {
            fillid.add(str.split(",")[0]);
            fillvalues.add(str.split(",")[1]!=null?str.split(",")[1]:"");
            }
        }

Upvotes: 1

Related Questions