29

I have an int variable and when I am setting this variable as an Android TextView's text it's throwing an error, maybe because it's an Int. I have checked but couldn't find a toString function for the int. So how can I do that?

int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(sdRate); //gives error
Peter O.
  • 32,158
  • 14
  • 82
  • 96

6 Answers6

98

Use String.valueOf():

int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(String.valueOf(sdRate)); //no more errors
Konstantin Burov
  • 68,980
  • 16
  • 115
  • 93
13

Use the Integer class' static toString() method.

int sdRate=5;
text_Rate.setText(Integer.toString(sdRate));
fabian
  • 80,457
  • 12
  • 86
  • 114
Scott M.
  • 7,313
  • 30
  • 39
4

You can use

text_Rate.setText(""+sdRate);
Kalu Khan Luhar
  • 1,044
  • 1
  • 22
  • 35
2

Did you try:

text_Rate.setText(String.valueOf(sdRate));
MBU
  • 4,998
  • 12
  • 59
  • 98
  • 1
    i *think* that since java has a mixed model concerning primitives and classes that you can't call any methods directly on an int. You must either use the Integer class' static toString() or cast it to an Integer first then call toString() on that. – Scott M. Jan 30 '11 at 06:47
  • Sorry the last one wouldnt work so i edited my answer. But, String.valueOf(sdRate) does work. – MBU Jan 30 '11 at 06:52
1

You have two options:

1) Using String.valueOf() method:

int sdRate=5;
text_Rate.setText(String.valueOf(sdRate));  //faster!, recommended! :)

2) adding an empty string:

int sdRate=5;
text_Rate.setText("" + sdRate)); 

Casting is not an option, will throw a ClassCastException

int sdRate=5;
text_Rate.setText(String.valueOf((String)sdRate)); //EXCEPTION!
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
0

may be you should try like this

int sdRate=5;
//text_Rate is a TextView
text_Rate.setText(sdRate+""); //gives error
Shijilal
  • 2,175
  • 10
  • 32
  • 55