-1

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?

tr_quest
  • 735
  • 2
  • 10
  • 24

2 Answers2

2

Your TableRow is null as you haven't instantiate it. try to instantiate it like this rowArr[i]=new TableRow();

for ( int i =0 ; i < gridSize ; i++){

    rowArr[i]=new TableRow();
        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]);
    }
Pragnani
  • 20,075
  • 6
  • 49
  • 74
2

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);
d3m0li5h3r
  • 1,957
  • 17
  • 33