Assigning Data to TableLayout Pragmatically Crashes app when launching

I have a table layout in XML with a row and three textviews in it. parsing data in table dynamically from an array but when I launch app it crashes. here is my code

TableLayout historyEntries = (TableLayout)findViewById(R.id.DataTable);
        historyEntries.setStretchAllColumns(true);
        historyEntries.bringToFront();
        for(int i = 0; i < dataArray.length; i++){
            TableRow tr =  (TableRow) findViewById(R.id.datarow);
            TextView c1 = (TextView) findViewById(R.id.TextView1);
            TextView c2 = (TextView) findViewById(R.id.TextView2);
            TextView c3 = (TextView) findViewById(R.id.TextView3);
            c1.setText(dataArray[i]);
            c2.setText(String.valueOf(dataArray[i]));
            c3.setText(String.valueOf(dataArray[i]));
            tr.addView(c1);
            tr.addView(c2);
            tr.addView(c3);
            historyEntries.addView(tr);
        }

Error

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

1 answer

  • answered 2018-11-08 08:24 Aaron

    A view can have one and only parent. It is likely that one or all of your views have parent, judging by findViewById call. If your views are already inflated in activity, simply drop these lines:

    tr.addView(c1);
    tr.addView(c2);
    tr.addView(c3);
    historyEntries.addView(tr);
    

    Otherwise, you can create a separate layout file with the TableRow and the TextView if you intend to add more rows:

    for (int i = 0; i < dataArray.length; i++){
        View v = LayoutInflater.from(context).inflate(R.layout.your_table_row, historyEntries, false);
        TableRow tr =  (TableRow) v.findViewById(R.id.datarow);
        TextView c1 = (TextView) v.findViewById(R.id.TextView1);
        TextView c2 = (TextView) v.findViewById(R.id.TextView2);
        TextView c3 = (TextView) v.findViewById(R.id.TextView3);
        c1.setText(dataArray[i]);
        c2.setText(String.valueOf(dataArray[i]));
        c3.setText(String.valueOf(dataArray[i]));
        historyEntries.addView(tr);
    }