1

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());
}
asked Dec 7, 2010 at 18:26
1
  • You may want to use String.format to apply formatting to the number is being displayed. Commented Dec 7, 2010 at 18:31

5 Answers 5

4
txtAnswer.setText(String.valueOf(result));

or this works also:

txtAnswer.setText("result is : "+result);
answered Dec 7, 2010 at 18:29
Sign up to request clarification or add additional context in comments.

6 Comments

Interesting, so if I wanted to extend this to do a simple calc:
why doesn't this work? int result = 14 * Integer.valueOf(editStones);
editStone is an EditText object, you need to do editStone.getText() to get the string content (a String object). So the correct syntax is : int result = 14 * Integer.ValueOf(editStone.getText());
That makes total sense, except it's highlighting 'valueOf' and telling me: The method valueOf(String) in the type Integer is not applicable for the arguments (Editable)
sorry then, should have checked it... it's editStone.getText().toString()
|
3

Use String.valueOf(result)

answered Dec 7, 2010 at 18:27

Comments

1

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).

answered Dec 7, 2010 at 18:30

Comments

0

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().

answered Dec 7, 2010 at 18:30

Comments

0

You can convert it using many formats as follows-

  1. Convert using Integer.toString(int)

    int number = -782;
    String numberAsString = Integer.toString(number);
    
  2. Convert using String.valueof(int)

    String.valueOf(number);
    
  3. Convert using Integer(int).toString()

    String numberAsString = new Integer(number).toString();
    
  4. Convert using String.format()

    String numberAsString = String.format ("%d", number);
    
Armali
19.6k15 gold badges64 silver badges185 bronze badges
answered Mar 19, 2019 at 6:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.