Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextView.setText(int) causes app to crash

I was implementing the following Java code in Android Studio:

private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
    quantityTextView.setText(number);
    ...
}

This is a part of a larger application.

As you can see, I've passed only an integer value to the quantityTextView.setText(number) method.

When running the app, it crashes as soon as this method is called. Can you tell me why such a thing is happening?

like image 212
Kanishk Kumar Gupta Avatar asked Jan 06 '17 17:01

Kanishk Kumar Gupta


2 Answers

Yes, use String.valueOf(), like this:

private void display(int number) {
    TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
    quantityTextView.setText(String.valueOf(number));
}
like image 103
omriherman Avatar answered Sep 24 '22 14:09

omriherman


Because setText() accepts only String values or Resource ID of a String (which is infact int).

Check here: setText() Method

You can use String.valueOf(number); as input parameter of setText() or you can refer to String ID in XML with getResources().getString(R.string.number) as input value.

like image 37
David Kasabji Avatar answered Sep 23 '22 14:09

David Kasabji