rakeshmenon
rakeshmenon

Reputation: 43

problem in array of button

I am creating a dynamic array of buttons, 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);
 }

Upvotes: 0

Views: 210

Answers (3)

Madhav Kishore
Madhav Kishore

Reputation: 279

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

Upvotes: 0

Codemonkey
Codemonkey

Reputation: 3412

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.

Upvotes: 0

Tobias
Tobias

Reputation: 7380

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

Upvotes: 2

Related Questions