-2

I have multiple buttons in my app and I want to set the same text for every button using a loop. So I declared an array and filled it with the buttons in this manner:

public class MainActivity extends AppCompatActivity {
    Button b1,b2,b3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1=(Button)findViewById(R.id.button);
        b2=(Button)findViewById(R.id.button2);
        b3=(Button)findViewById(R.id.button3);
    }

    Button[] buArray ={b1,b2,b3};

    void b1clicked(View view) {
        for (int i =0;i<3;i++) {
            buArray[i].setText("it works");
        }
    }
}

But when i try to set text for a button from the array like this

buArray[0].setText("some text");

This causes my app to crash and force closes And gives me an error like this in the the log "NullPointerException

petey
  • 16,914
  • 6
  • 65
  • 97

1 Answers1

1

Since your Button[] buArray ={b1,b2,b3}; is outside of the methods, it is initialized when the Activity object is created. At that point, b1, b2 and b3 are all null.

Move the initialization into the onCreate() method and it will work.

Button b1,b2,b3;
Button[] buArray;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b1=(Button)findViewById(R.id.button);
    b2=(Button)findViewById(R.id.button2);
    b3=(Button)findViewById(R.id.button3);
    buArray = new Button[] {b1, b2, b3};  
}
Ridcully
  • 23,362
  • 7
  • 71
  • 86