addView()方法抛出Nullpointer异常

时间:2013-05-08 10:12:35

标签: android android-view android-tablelayout

我正在尝试使用表格布局

以编程方式实例化一行按钮
    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);
}

然而,这一行似乎抛出了一个nullpointerexception

     rowArr[i].addView(button);

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您的TableRownull,因为您尚未实例化它。 尝试像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]);
    }

答案 1 :(得分:2)

你已经初始化了rowArr数组,但没有初始化它的单个TableRow元素。所以rowArr [i]将为null。在for循环中,将以下行放入其中: -

rowArr[i] = new TableRow(this);