How can I convert the below int to display the result of the sum as text in a textview?
Am getting 'cannot invoke toString() on primitive type int' - thought that was the point of toString!?!
public void onClick(View v) {
// TODO Auto-generated method stub
txtAnswer = (TextView)findViewById(R.id.txtAnswer);
editStones = (EditText)findViewById(R.id.editStones);
int result = 10 + 10;
txtAnswer.setText(result.toString());
}
5 Answers 5
txtAnswer.setText(String.valueOf(result));
or this works also:
txtAnswer.setText("result is : "+result);
6 Comments
Use String.valueOf(result)
Comments
int is a primitive type in Java, meaning it is not a class, and therefore has no toString() method. You can use the Integer class or just use String.valueOf(result).
Comments
One of the more annoying things about java is that they still have primitives. So you have to use a Static Method of another class, either String.valueOf() or Integer.toString().
Comments
You can convert it using many formats as follows-
Convert using Integer.toString(int)
int number = -782; String numberAsString = Integer.toString(number);Convert using String.valueof(int)
String.valueOf(number);Convert using Integer(int).toString()
String numberAsString = new Integer(number).toString();Convert using String.format()
String numberAsString = String.format ("%d", number);
String.formatto apply formatting to the number is being displayed.