按钮数组中的问题

时间:2011-04-01 07:14:13

标签: android

我正在创建一个动态的按钮数组,但我得到的是Nullpointer Exception。为什么? 我的示例代码是:

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

3 个答案:

答案 0 :(得分:2)

因为你没有初始化你的数组,试试这个:

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

答案 1 :(得分:0)

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

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

编辑:删除此内容非常愚蠢。

答案 2 :(得分: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);