Incredibly simple android java question
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());
}
txtAnswer.setText(String.valueOf(result));
or this works also:
txtAnswer.setText("result is : "+result);
Use String.valueOf(result)
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).
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().
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);
精彩评论