2

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
1
  • follow the steps of azgolfer. It solves your problem Commented Aug 14, 2012 at 17:59

2 Answers 2

10

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]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.