开发者

problem in array of button

开发者 https://www.devze.com 2023-02-21 14:33 出处:网络
I am creating a dynamic array of but开发者_如何学Ctons, but i am getting Nullpointer Exception. Why?

I am creating a dynamic array of but开发者_如何学Ctons, but i am getting Nullpointer Exception. Why? My sample code is:

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


Because you didn´t initialized your array, try this:

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


You aren't initializing the array itself, only the elements inside? See line 2:

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

Edit: Pretty silly of me to delete this.


The following code should help you out:

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消