简体   繁体   中英

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?

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));
}

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.

Convert the integer to string before putting it in the TextView:

quantityTextView.setText(Integer.toString(number));

or simply

quantityTextView.setText(number+"");

The reason your code is crashing is that setText(int) expects a resource ID . It's not very well documented, so you'd be forgiven for thinking that you could pass it an integer and have the TextView convert it to text.

You should first convert it to a String, for example with:

String.valueOf(number)

and then it will be alright.

setText() method of TextView accepts CharSequence, not integers. So, you must convert your number to String before.

Try to use this:

quantityTextView.setText(Integer.toString(x));

The reason is that, setText() only expects string or char[].

So either you can perform type casting or you can add quotes with the number

(1). by type casting String.valueOf(number)

(2). by adding "" with the number quantityTextView.setText(""+number); or quantityTextView.setText(number+"");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM