开发者

setOnClickListener throws NullPointerException ONLY inside for loop. Why?

private final Button[] BUTTONS = {
    btn1, btn2, btn3,btn4
};

...

btn1 = (Button) this.findViewById(R.id.btn_1);
btn2 = (Button) this.findViewById(R.id.btn_2);
btn3 = (Button) this.findViewById(R.id.btn_3);
btn4 = (Button) this.findViewById(R.id.btn_4);

...

int n = BUTTONS.length;
for(int i=0; i<n; i++) {
    if(DEBUG) Log.d(TAG, String.valueOf(i));
    BUTTONS[i].setOnClickListener(this)开发者_StackOverflow社区;
}

throws NullPointerException, whereas

btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);

works fine. Doesn't make any sense to me.


I think it's because your Buttons array is created when btn1,... are still null.

So when you call BUTTONS[i].setOnClickListener in the loop you are really saying null.setOnClickListener which will give an exception.

Try setting up the array as a variable and sey AFTER you've assigned btn1, etc.

Haven't tested it but something like this might work better...

private ArrayList mBtns = new ArrayList();

private void initButton(int id) { button = (Button) findViewById(id); button.setOnClickListener(this); mBtns.add(button); }

...

initButton(R.id.btn_1); initButton(R.id.btn_2); initButton(R.id.btn_3); initButton(R.id.btn_4);

Also unless the buttons do very similar things you may find it better to simply define the onClick attribute on each in the layout and save yourself A LOT of coding (only available in Android 1.6 and higher).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜