5

I'd like to try to set string array as text of the textview. How can I do that?

Below is what I've tried so far:

String[] word = { "Pretty", "Cool", "Weird" };

tv.setText( word.length );

But it's throwing some errors. I'm new to Android/Java

1
  • 2
    You are setting lenght, not the array. Tried Arrays.toString(word);?? Commented Oct 13, 2012 at 13:40

2 Answers 2

23

word.length gives you length of the array, not the content. You mean to set the content to tv. You can use Arrays#toString method: -

String[] word = { "Pretty", "Cool", "Weird" };

// Prints [Pretty, Cool, Weird]
tv.setText(Arrays.toString(word));   

// Prints Pretty, Cool, Weird
tv.setText(Arrays.toString(word).replaceAll("\\[|\\]", ""));
Sign up to request clarification or add additional context in comments.

Comments

7

TextView.setText() takes a CharSequence as the first argument so the compiler will complain if you pass in an int in the case of word.length.

Using an enhanced for-loop:

String[] word = { "Pretty", "Cool", "Weird" };
StringBuilder builder = new StringBuilder();
for (String s: word) {
    builder.append(s);
    builder.append(" ");
}

tv.setText(builder.toString().trim()); // .trim to remove the trailing space.

or since Java 8:

tv.setText(String.join(" ", word));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.