This block of code does not work for me. I debugged and I think the error is coming from the setlayoutparams but it doesn't make sense because if I take out the for loop and create just 1 button (not an array of buttons) then it'll work.
Button btn[] = new Button[oNumber];
for (int i=0;i<oNumber;i++){
btn[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
btn[i].setText(oName[i]);
System.out.println("making b's");
layout.addView(btn[i]);
}
This is the error I get. I do have the activity correctly written in the manifest.
08-14 12:45:56.482: E/AndroidRuntime(4060): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rcontrol/com.example.rcontrol.ViewTarget}: java.lang.NullPointerException
You created the array of buttons but did not initialize it:
Button btn[] = new Button[oNumber];
for (int i=0;i<oNumber;i++){
btn[i] = new Button(this); // initialize it
btn[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
btn[i].setText(oName[i]);
System.out.println("making b's");
layout.addView(btn[i]);
}
for more Detail.
int oNumber = 4;
String oName[] = {"x","2","3","4"};
Button btn[] = new Button[oNumber];
LinearLayout layout = (LinearLayout) findViewById(R.id.layout1);
for (int i=0;i<oNumber;i++){
btn[i] = new Button(this); // initialize it
btn[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
btn[i].setText(oName[i]);
btn[i].setOnClickListener(this);
System.out.println("making b's");
layout.addView(btn[i]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With