Reputation: 2645
I am using this to try to display all the characters in the array but all it prints is "g" I tested the same code using System.out.println() in regular java and it works fine
String testarray[]={"a","s","d","f","g"};
for(int l=0; l<testarray.length; l++){
String temp="";
temp=temp+testarray[l];
display.setText(""+temp);
}
Thanks!
Upvotes: 0
Views: 8592
Reputation: 16228
By your code, I will avoid what others are saying and I'll explain to you in simple laymen terms:
In plain english, there is a difference between set and print.
When you set something, you replace whatever was there with a new value. When you print, you append something to whatever was there. System.out.print
thus appends stuff, while setText
sets stuff instead.
The for
happens so fast (computer can compute gazillion stuffs faster than you can blink) that you see a bunch of setText
stuff in succession, and end up with only "g". That's why you need, as others said, to "append" stuff.
However, simpler than what others have said, there is only one line that you need inside this whole for loop.
display.setText(display.getText() + testarray[l]);
And that is all you need.
Upvotes: 2
Reputation: 4387
The best way to do this, is with a for-each loop.
Try:
TextView tv = (TextView) findViewById(R.id.TextView);
String testarray[] = {"a","s","d","f","g"};
String print = "";
for(String s : testarray) {
print += s;
}
tv.setText(print)
This will print out asdfg
The problem in your code is you initialize the variable WITHIN the for loop, meaning for each time it goes through, it remakes the String = "", to fix this initialize it like I do in my example. Also, don't set the textview until after the loop.
If you're not familiar with the for-each loop, its basically:
for each ( object x in objectArray)
do this
EDIT:
System.out.println() != .setText()
.setText() SETS the text of the view, every time you reset the text, you do exactly that, remove the old text, and add the new
Upvotes: 2
Reputation: 34026
You are doing wrong way.You are initializing the temp string with empty string in for loop. So every time it will be assign empty string and then you are concating the string from array so temp string will have only String which you are assigning from array and then you are displaying on textview.
This way you can set all the character by creating string on Textview
String testarray[]={"a","s","d","f","g"};
String temp="";
for(int l=0; l<testarray.length; l++){
temp=temp+testarray[l];
}
display.setText(temp);
Upvotes: 0