title: Adding Table rows Dynamically in Android
body: <p>I am trying to create a layout where I need to add table rows dynamically. Below is the table layout xml</p>
  
  <pre><code>&lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:id="@+id/displayLinear"
      android:background="@color/background_df"
      android:orientation="vertical" &gt;
  
           &lt;TableRow
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:id="@+id/display_row"
              android:layout_marginTop="280dip" &gt;
  
  &lt;/TableLayout&gt;
  </code></pre>
  
  <p>The activity file where rows are being added dynamically is</p>
  
  <pre><code>public void init(){
      menuDB = new MenuDBAdapter(this);
      ll = (TableLayout) findViewById(R.id.displayLinear);
  
      TableRow row=(TableRow)findViewById(R.id.display_row);
      for (int i = 0; i &lt;2; i++) {
  
          checkBox = new CheckBox(this);
          tv = new TextView(this);
          addBtn = new ImageButton(this);
          addBtn.setImageResource(R.drawable.add);
          minusBtn = new ImageButton(this);
          minusBtn.setImageResource(R.drawable.minus);
          qty = new TextView(this);
          checkBox.setText("hello");
          qty.setText("10");
          row.addView(checkBox);
          row.addView(minusBtn);
          row.addView(qty);
          row.addView(addBtn);
          ll.addView(row,i);
  
      }
  }
  </code></pre>
  
  <p>But when I run this, I am getting below error</p>
  
  <pre><code>08-13 16:27:46.437: E/AndroidRuntime(23568): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.roms/com.example.roms.DisplayActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
  </code></pre>
  
  <p>I understand that this is due to command <code>ll.addView(row,i);</code> but when I remove this its adding all stuff in a single row rather tan creating a new row for next item. I tried with giving index too as <code>row.addView(addBtn,i)</code> but still its not populating correctly. Please advise. Thanks.</p>