I am making an app that in order to save time, saves buttons in an array, but can't seem to add onClickListener to the buttons on the array.
when I replace the loop that adds the onClickListener by
buttons[0].setOnClickListener;
button[1].setOnClickListener;
the code works fine but when I replace it with this loop shown below
for (int i = 0; i < 91; i++)
buttons[i].setOnClickListener(this);
I get this error "Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference" on the line inside the for loop.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
board = (TableLayout) findViewById(R.id.tableLayout);
bar = (TableLayout) findViewById(R.id.tableLayout2);
buttons = new Button[91];
for (int i = 2; i < 93; i++) {
String str = "button" + i;
if (i != 6) {
button = findViewById(getResources().getIdentifier(str, "id", getPackageName()));
buttons[i - 2] = button;
}
}
text = findViewById(R.id.textView2);
for (int i = 0; i < 91; i++) {
buttons[i].setOnClickListener(this);
}
}
I expected the onClickListener loop to work but whenever I try to load the activity which these buttons are placed in my application crashes