I am trying to instantiate a row of Buttons Programatically using Table Layout
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private final int gridSize = 3;
private TableRow rowArr[] = new TableRow[gridSize];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create the layout
TableLayout MainLayout = new TableLayout(this);
MainLayout.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.MATCH_PARENT));
//MainLayout.setStretchAllColumns(true);
for ( int i =0 ; i < gridSize ; i++){
for(int j = 0; j < gridSize ; j++){
Button button = new Button(this);
button.setText(Integer.toString(i)+","+Integer.toString(j));
rowArr[i].addView(button);
}
MainLayout.addView(rowArr[i]);
}
//Set the view
setContentView(MainLayout);
}
However this line seems to throw a nullpointerexception
rowArr[i].addView(button);
What am i doing wrong?
you have initialized the rowArr array but not the individual TableRow element of it. so rowArr[i] will be null. in the for loop, put the following line in it:-
rowArr[i] = new TableRow(this);