Rhiokai
Rhiokai

Reputation: 2167

setText of a TextView array

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.

Upvotes: 0

Views: 1074

Answers (2)

Yevgeny Simkin
Yevgeny Simkin

Reputation: 28349

Without further info as to where you're setting etName (which is almost certainly your problem) it's hard to know where you're getting your null (your stack trace will give you a line number which should tell you that, btw) but aside from that you should not put an array of fields together as you are doing and then setting the number 8 as a hard coded number in your activity. Rather, you should first loop through your activity and construct that array based on how many Views you have that are named nameX (where X is a number that goes from 0 upwards as many times as you want). That way you will always have the exact right number of iterations.

If you don't know how to look for Views based on their XML id, chime in and I will add the code for that.

Upvotes: 0

Sam
Sam

Reputation: 86948

It appears your haven't properly initialized your array, since nameList[i] is null. Try:

nameList[0] = (TextView) findViewById(R.id.text1);
nameList[1] = (TextView) findViewById(R.id.text2);
// etc

Upvotes: 2

Related Questions