What I’m trying to do is have an EditText where people enter their names. As people press the “Add Player” button, the name which they just typed appears below in the list form. So I’ve created 8 textviews which are initially invisible but as people type the name press the “Add Player” button, the text changes to their names and becomes visible.
So I set up a TextView array of the list of names, which are all text views
TextView[] nameList = new TextView[]{name1, name2, name3, name4, name5, name6, name7, name8};
Later on in the code in the onClick section, I had
for (int i = 0; i < 8; i++) {
String name = etName.getText().toString();
nameList[i].setText(name);
nameList[i].setVisibility(View.VISIBLE);
}
However, with this, whenever I press the “add player” button, the app crashes and I get a NullPointerException. How would I solve this?
The problem isn’t with the for loop as the app crashed without it. The problem seems to be with the array as if I put
name1.setText(name);
name1.setVisibility(View.VISIBLE);
the code worked fine.
It appears your haven’t properly initialized your array, since
nameList[i]is null. Try: