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