2011-04-01 67 views
0

我正在创建一个动态的按钮数组,但我得到的是空指针异常。为什么? 我的示例代码:按钮阵列的问题

Button addAsFriend[]; 
for(i=0;i<c.getCount();i++) 
{ 
    addAsFriend[i]=new Button(this); 
} 

回答

2

因为你didn't初始化您的数组,试试这个:

Button addAsFriend[] = new Button[c.getCount()]; 
for(i=0;i<c.getCount();i++) 
{ 
    addAsFriend[i] = new Button(this); 
} 
+0

感谢的作品 – rakeshmenon 2011-04-01 07:37:13

+0

我如何可以实现为每个点击事件这个数组中的按钮 – rakeshmenon 2011-04-01 07:38:08

+0

请为此问题启动一个新线程 – Tobias 2011-04-01 07:40:42

0

您还没有初始化数组本身,只是里面的元素呢?见第2行:

Button addAsFriend[]; 
addAsFriend = new Button[c.GetCount()]; 
    for(i=0;i<c.getCount();i++) 
     { 
      addAsFriend[i]=new Button(this); 
     } 

编辑:我很愚蠢的删除这个。

0

下面的代码应该帮助你:

Button[] b = new Button[9]; 
b[0] = (Button) findViewById(R.id.button1); 
b[1] = (Button) findViewById(R.id.button2); 
b[2] = (Button) findViewById(R.id.button3); 
b[3] = (Button) findViewById(R.id.button4); 
b[4] = (Button) findViewById(R.id.button5); 
b[5] = (Button) findViewById(R.id.button6); 
b[6] = (Button) findViewById(R.id.button7); 
b[7] = (Button) findViewById(R.id.button8); 
b[8] = (Button) findViewById(R.id.button9);