Why Does Adding An Empty String Fix My TextView.setText()?
Solution 1:
score is of type int. The setText method that you want to use expects something of type char[], i.e, a string. Note that another setText method does expect an integer, which is used to find a resource through its ID. This is why you don't get an error when using setText(score).
Knowing this:
- On
text.setText(score);, if you convertscoreto a string, it will work (for instance, usingInteger.toString(score)). - On
text.setText("" + score);, you already have the""string, and Java understands that you're trying to append an integer to a string, so it returns a string. This version, however, is not efficient, since everytime you concatenate something to a string, you're creating a new string (this is why people useStringBuilder).
Long story short, just convert score to a string.
Solution 2:
You're using two different versions of setText():
- The one taking an int: https://developer.android.com/reference/android/widgetTextView.html#setText(int)
- The one taking a CharSequence (e.g. a String): https://developer.android.com/reference/android/widget/TextView.html#setText(java.lang.CharSequence)
The first one takes a resource id. The TextView will try to load that resource as a string. Since you're supplying an arbitrary int, you're probably getting a "Resource Not Found" exception.
The second one takes a CharSequence, and will simply display that exact text.
Changing the argument to "" + score will create a string containing the appropriate characters to display the score value.
Post a Comment for "Why Does Adding An Empty String Fix My TextView.setText()?"