dynamic table layout table row content is not working

jyo abc :

Hi in the below code I am implementing dynamic table layout. dynamically added table row names also added dynamically.

trying adding the content to the rows.but it is throwing an exception array index out of bound exception.

can any one help me where i did the mistake

    java.lang.ArrayIndexOutOfBoundsException: length=3; index=3

Code

 String productValues = listSalesStageOpportunity.get(position).getProductValue();
TableLayout stk = (TableLayout) customView.findViewById(R.id.tables);
        TableRow tbrow0 = new TableRow(getContext());
        TextView tv0 = new TextView(getContext());
        tv0.setText(" Sl.No ");
        tv0.setTextColor(Color.WHITE);
        tbrow0.addView(tv0);
        TextView tv1 = new TextView(getContext());
        tv1.setText(" Item Name ");
        tv1.setTextColor(Color.WHITE);
        tbrow0.addView(tv1);
        TextView tv2 = new TextView(getContext());
        tv2.setText(" Unit Price ");
        tv2.setTextColor(Color.WHITE);
        tbrow0.addView(tv2);
        TextView tv3 = new TextView(getContext());
        tv3.setText(" Total ");
        tv3.setTextColor(Color.WHITE);
        tbrow0.addView(tv3);
        stk.addView(tbrow0);
        for (int i = 0; i < productValues.length(); i++) {
            TableRow tbrow = new TableRow(getContext());
            TextView t1v = new TextView(getContext());
            String[] namesList = productValues.split(",");
            t1v.setText(namesList[i]);//error
            t1v.setTextColor(Color.WHITE);
            t1v.setGravity(Gravity.CENTER);
            tbrow.addView(t1v);
stk.addView(tbrow);
        }
Ink Archer :

ProductValues.length() is returning an unreachable value of 4 (out of 13).

If there are only 3 items (falco,cs30,bs) the max value for i is 2, but i is equals to 3 according the exception.

If productValues = "falco,cs30,bs". The call productValues.length() returns 13. You array does not have 13 items.

you should move the split method up, before the for loop, and use its result as the loop iterator.

String[] namesList = productValues.split(",");
for (int i = 0; i < namesList.length(); i++) 
{
        TableRow tbrow = new TableRow(getContext());
        TextView t1v = new TextView(getContext());
        t1v.setText(namesList[i]);
        t1v.setTextColor(Color.WHITE);
        t1v.setGravity(Gravity.CENTER);
        tbrow.addView(t1v);
        stk.addView(tbrow);
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=389226&siteId=1