Skip to content Skip to sidebar Skip to footer

Why Does Adding An Empty String Fix My TextView.setText()?

i'm trying to make a simple app which adds 3 in display,just got confused in one part this doesn't work in my phone and showing some error. public void addThreeToTeamA(View view)

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 convert score to a string, it will work (for instance, using Integer.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 use StringBuilder).

Long story short, just convert score to a string.


Solution 2:

You're using two different versions of setText():

  1. The one taking an int: https://developer.android.com/reference/android/widgetTextView.html#setText(int)
  2. 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()?"