-1
    public void save(View view)
    {
        if (!editText.getText().toString().matches(""))
        {
            int userAge = Integer.parseInt(editText.getText().toString());
            textView.setText(""+userAge);
        }
    }

this code work with VM but if i change part of

textView.setText(""+userAge);

this to this

textView.setText(userAge);

onclick method shutdown app on VM both code work same goal, but i don't understand why second row doesn't work

3 Answers3

1

You can't use setText with integer inside. You first need to convert it to a string. There is two options, textView.setText(""+userAge);, textView.setText(String.valueOf(userAge));

moxy
  • 314
  • 1
  • 6
0

You cannot use an int as a string. You have to use .ToString(), or adding the string before, as you did at the first row.

0

TextView.setText(int) will set the text to a resource ID corresponding to a string resource defined in your strings.xml. Here, when you do textView.setText(userAge), you are calling this method, but userAge is not a valid string resource ID, so it crashes.

However, when you do TextView.setText(""+userAge), you are converting the int to a String, just not in a conventional way. Concatenating anything to a string implicitly calls .toString() on the object, and String.valueOf for primitives. But instead of TextView.setText(""+userAge), you can do TextView.setText(String.valueOf(userAge)), which is cleaner.

Nicolas
  • 5,182
  • 2
  • 22
  • 58