Search code examples
androidandroid-layoutandroid-tablelayout

Getting exception when inserting tablerow through code in a TableLayout


I am trying to insert rows from my code in a TableLayout. I got several tutorials on internet and stackOverflow and some how each time i get this exception.

12-12 17:54:07.027: E/AndroidRuntime(1295): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

12-12 17:54:07.027: E/AndroidRuntime(1295):     at com.kaushik.TestActivity.onCreate(TestActivity.java:41)

Here is the activityclass:

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        /* Find Tablelayout defined in main.xml */
        TableLayout tl = (TableLayout) findViewById(R.id.myTableLayout);
        /* Create a new row to be added. */
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        /* Create a Button to be the row-content. */
        Button b = new Button(this);
        b.setText("Dynamic Button");
        b.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
        /* Add Button to row. */
        tr.addView(b);
        /* Add row to TableLayout. */
        tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));

        /* adding another row */
        TableRow tr2 = new TableRow(this);
        tr2.addView(b); // Exception is here
        tl.addView(tr2, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.WRAP_CONTENT));
    }

and here is the XML

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/myTableLayout"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
</TableLayout>

Please help me.


Solution

  • Your are doing wrong with

     /* adding another row */
     TableRow tr2 = new TableRow(this);
     tr2.addView(b); // Exception is here
    

    B is a button , as its already added in your table 1st row "t1". As button is a view and each view can be hold by one parent only. The Button b is already shown to 1st row. Its can be show again on row2.

    As it don't make a logic when user click the button or row1 or row2 then how to know which button is pressed? I mean you can't know it is pressed by row 1 or row 2. So this is unexpected thing you are doing.

    As in

    onClick(View view){
       if(view == b){
           // So you cant do that this is button row1 button or row2 button.
       }
    
       // Or you can check the pressed button by id which will also be same. 
    
    }
    

    So you should create new Button button2 and then add to row2.