pileup
pileup

Reputation: 3270

How to programmatically update the variable to match the iteration

I have the following for-each loop:

for(DataSnapshot data: dataSnapshot.getChildren()){
    TextView textview = (TextView) findViewById(R.id.textview);
    String message = data.getKey().toString();
    textview.setText(message);
}

Now there are different textviews with ids textview1 textview2 textview3..etc (can grow and shrink). How do I do that in the for-each loop though? Using some counter and somehow concat it to the variable? I want the different messages to display in the different textviews

Upvotes: 1

Views: 79

Answers (1)

forpas
forpas

Reputation: 164099

You will have to modify your code like this:

int i = 1;
for(DataSnapshot data: dataSnapshot.getChildren()){
    int id = getResources().getIdentifier("textview" + i, "id", getPackageName());
    TextView textview = (TextView) findViewById(id);
    String message = data.getKey().toString();
    textview.setText(message);
    i++;
}

with getResources().getIdentifier("textview" + i, "id", getPackageName()); you find the integer id of a View by using its name id.
You may have to supply a Context to getResources() like:

context.getResources().getIdentifier("textview" + i, "id", context.getPackageName());

if this code is not inside an activity.

Upvotes: 3

Related Questions