I have a need to create more than one TableLayout with a varied number of rows in one XML layout.
In my main layout I have an empty LinearLayout, as shown below:
<LinearLayout android:id="@+id/resultsLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
I declare this in my activity as so:
private LinearLayout linearResultsLayout;
linearResultsLayout = (LinearLayout) findViewById(R.id.resultsLayout);
I have added a table_layout.xml and a table_row.xml to my Layouts folder:
Table_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/resultsTable"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:weightSum="99"
android:background="@drawable/curvedbg"
>
</TableLayout>
Table_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView android:id="@+id/row_header" android:layout_weight="33" />
<TextView android:id="@+id/downstream" android:layout_weight="33"/>
<TextView android:id="@+id/upstream" android:layout_weight="33"/>
</TableRow>
My aim is to inflate the table and then inflate how ever many rows I require in to the newly inflated table whilst also passing data in the form of TextViews. The code below should give you an idea of what I'm trying to do. It doesn't work, however. NullPointerException.
private void createTable() {
String[] downResults = {"Downstream","2000","98"};
String[] upResults = {"Upstream","1000","78"};
String[] rowHeadings = {"","Bandwidth","QoS"};
TextView heading = (TextView) findViewById(R.id.row_header);
TextView downstream = (TextView) findViewById(R.id.downstream);
TextView upstream = (TextView) findViewById(R.id.upstream);
TableLayout newTable = (TableLayout) findViewById(R.id.resultsTable);
View table = inflater.inflate(R.layout.table_layout, null);
View row = inflater.inflate(R.layout.table_row, null);
linearResultsLayout.addView(table);
for(int i = 0; i < rowHeadings.length; i++){
heading.setText(rowHeadings[i].toString());
downstream.setText(downResults[i].toString());
upstream.setText(upResults[i].toString());
newTable.addView(row);
}
}
I assume it will be more complicated than how I'm trying to accomplish it.
You should probably use a ListView:
But, assuming you can't / won't, the problem you have is that you are referencing the wrong layout when you get your
TextView
objects. Your code should probably look more like this:Notice the
row.findViewById
and also thetable.addView
EDIT: note the change in the layout inflater