Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not create array of buttons programatically without an error

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
like image 219
zms6445 Avatar asked Nov 22 '25 16:11

zms6445


2 Answers

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]);
}
like image 158
azgolfer Avatar answered Nov 25 '25 06:11

azgolfer


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]);
    }
like image 44
UmAnusorn Avatar answered Nov 25 '25 05:11

UmAnusorn