Search code examples
androidandroid-layoutandroid-viewandroid-button

Android OnClickListener throws NullPointerException


A table is being created such that:

    TableLayout layout = new TableLayout(this);
    layout.setLayoutParams(new TableLayout.LayoutParams(4,5));
    layout.setPadding(1, 1, 1, 1);

    for(int i=0; i<7; i++) {
        TableRow tr = new TableRow(this);
        for(int j=0; j<6; j++) {
            Button b = new Button(this);
            b.setText("0");
            b.setOnClickListener(buttonListener);
            tr.addView(b);
        }
        layout.addView(tr);
    }

    super.setContentView(layout);

The OnClickListener buttonListener is:

View.OnClickListener buttonListener = new View.OnClickListener() {
    public void onClick(View v) {
        Button thisButton = (Button) findViewById(((Button)v).getId());
        //thisButton.setText(Integer.toString(Integer.parseInt((String) thisButton.getText()) + 1));
        thisButton.getText();
    }
};

The call to thisButton.getText() throws a NullPointerException, and I'm not sure why. Can anyone help me out?


Solution

  • One problem in your code.

    Have not set id of Button

            b.setText("0");
            b.setOnClickListener(buttonListener);
            b.setId(i);