Check this out, this is the general way of creating table rows dynamically. Modify it accordingly
XML file
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_table"
android:layout_height="wrap_content"
android:layout_width="match_parent">
</TableLayout>
JAVA PART
TableLayout t1;
TableLayout tl = (TableLayout) findViewById(R.id.main_table);
Create table row header to hold the column headings
TableRow tr_head = new TableRow(this);
tr_head.setId(10);
tr_head.setBackgroundColor(Color.GRAY); // part1
tr_head.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
I'm adding two data sections to the table row
TextView label_hello = new TextView(this);
label_hello.setId(20);
label_hello.setText("HELLO");
label_hello.setTextColor(Color.WHITE); // part2
label_hello.setPadding(5, 5, 5, 5);
tr_head.addView(label_hello);// add the column to the table row here
TextView label_android = new TextView(this); // part3
label_android.setId(21);// define id that must be unique
label_android.setText("ANDROID..!!"); // set the text for the header
label_android.setTextColor(Color.WHITE); // set the color
label_android.setPadding(5, 5, 5, 5); // set the padding (if required)
tr_head.addView(label_android); // add the column to the table row here
After adding the columns to the table row its time to add the table row the the main table layout that we fetched at the start
tl.addView(tr_head, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, //part4
LayoutParams.MATCH_CONTENT));
EDIT : YOU CAN DO THE FOLLOWING IN YOUR CODE
TextView[] textArray = new TextView[productsList.length()];
TableRow[] tr_head = new TableRow[productsList.length()];
for(int i=0; i<productsList.length();i++){
JSONObject product = productsList.getJSONObject(i);
JSONObject productData = product.getJSONObject("Product");
String productDescription = productData.getString("description");
//Create the tablerows
tr_head[i] = new TableRow(this);
tr_head[i].setId(i+1);
tr_head[i].setBackgroundColor(Color.GRAY);
tr_head[i].setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// Here create the TextView dynamically
textArray[i] = new TextView(this);
textArray[i].setId(i+111);
textArray[i].setText(productDescription);
textArray[i].setTextColor(Color.WHITE);
textArray[i].setPadding(5, 5, 5, 5);
tr_head[i].addView(textArray[i]);
// Add each table row to table layout
tl.addView(tr_head[i], new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
} // end of for loop
Creating the TextView and TableRow array are not necessary. You can just include part1
, part2
, part3
(if you need more than 1 field) and part4
inside your for loop.