2013-05-08 109 views
-1

我试图实例一排按钮编程方式使用表布局addView()方法抛出空指针异常

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

你初始化了rowArr数组,但不是它的个体的TableRow元素。所以rowArr [i]将为空。在for循环中,放入以下行: -

rowArr[i] = new TableRow(this); 
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]); 
    }