-4

Code 1:

public void displayQuantity(int number) {
    TextView quantityTV = (TextView) findViewById(R.id.quantity_tv);
    quantityTV.setText( " "+ number);
      }

Code 2:

 public void displayQuantity(int number) {
            TextView quantityTV = (TextView) findViewById(R.id.quantity_tv);
            quantityTV.setText(number);
         }

Why Code 2 gives error while code 1 doesn't?? There is a difference of - " __ " in b/w code 1 & 2

4 Answers4

1

According to the documentation

Code 1 uses the method setText(CharSequence text) which "sets the text to be displayed".

Code 2 uses the method setText(int resid) which "Sets the text to be displayed using a string resource identifier". Your number most likely is not a valid string resource identifier which gives you an error. Even if it was, the displayed string would have nothing to do with the quantity you want to display.

Henry
  • 42,982
  • 7
  • 68
  • 84
0

In TextView you can set only String(CharSequence) value and your number data type is in int if you do like this it will not show any error :

          public void displayQuantity(int number) {
            TextView quantityTV = (TextView) findViewById(R.id.quantity_tv);
            quantityTV.setText(String.valueOf(number));
         }
Abhinav Gupta
  • 2,225
  • 1
  • 14
  • 30
  • Not quite- setText has an int version- but it takes a resourceID to a string resource. And if the id passed doesn't match a string resource, it will throw an exception. That's what's happening here. – Gabe Sechan Dec 22 '18 at 06:27
  • @GabeSechan Yes I wrote this in short way.... – Abhinav Gupta Dec 22 '18 at 06:32
0

number is int type and + operator automatically converts it into String.("" is empty String)

+ operator for String in Java

Dhaval Goti
  • 447
  • 2
  • 10
  • 25
0

Try number.toString() in code 2 because you are doing string concatenation with an int in the

Sterben
  • 9
  • 2