0

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

Jack
  • 5,354
  • 2
  • 29
  • 54
  • 4
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Zoe Apr 02 '19 at 07:05
  • it's clear that not every element of your array contains an instantiated Button. Zoe is right: this is indeed a fancy way to say you have a NullPointerException – Stultuske Apr 02 '19 at 07:07
  • Why don't you use a recyclerView if you have an array of buttons. You are creating so many views for no reason and will lead to drastic performance. It is better to use a recycler view as it is the most efficient way to handle an array of same views. – Sarthak Gandhi Apr 02 '19 at 07:12
  • 'buttons = new Button[91]; for (int i = 3; i < 94; i++) { String str = "button" + i; button = findViewById(getResources().getIdentifier(str, "id", getPackageName())); buttons[i - 3] = button; buttons[i-3].setOnClickListener(this); }' this woks now. what is a recyclerView? – Eddie Cohen Apr 03 '19 at 12:17

1 Answers1

0

Make sure that every button you are using there is correctly instantiated before setting the listeners, you can set up a breakpoint or logging to check if everything is instantiated correctly.

Jack
  • 5,354
  • 2
  • 29
  • 54