kanga
kanga

Reputation: 35

How to have a TextView or EditText display a variable

I am trying to display the result of a calculation on a TextView or EditText. I get the users input from one100lbs and tenPounds and then add it together and am trying to display it on totalPounds. Its is not the equation I am going to use but just want to see that it works. Currently with the code below my application crashs. This is all under one activity. Also how come when I change the ID of a EditText the location of the editText changes on my relative layout? Please no links, i know its simple but I am a noob. I have searched and am having a hard time finding a solution.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.pounds);
    addListenerOnSpinnerItemSelection();

    EditText one100lbs = (EditText) findViewById(R.id.one100lbs);
    int one = Integer.valueOf(one100lbs.getText().toString());

    EditText tenPounds = (EditText) findViewById(R.id.tenPounds);
    int two = Integer.valueOf(tenPounds.getText().toString());

    int result = one + two;

    TextView textView = (TextView) findViewById(R.id.totalPounds);
    textView.setText(result);   
}

Upvotes: 0

Views: 4101

Answers (2)

A--C
A--C

Reputation: 36449

You want something like:

textView.setText(String.valueOf(result));

As it stands, Android is trying to find a resource id when you supply just an int, which will fail.

It has also occured to me that you're using EditTexts, which are notorious for failing when you input numbers, besides forcing the keypad to be only numbers, you can do something like:

int one = 0;
int two = 0;

try{
  EditText one100lbs = (EditText) findViewById(R.id.one100lbs);
  one = Integer.valueOf(one100lbs.getText().toString().trim());
}
catch (NumberFormatException e)
{
  one = -1;
}

try{
  EditText tenPounds = (EditText) findViewById(R.id.tenPounds);
  two = Integer.valueOf(tenPounds.getText().toString().trim()); 
}
catch (NumberFormatException e)
{
  two = -1;
}

int result = one + two;

TextView textView = (TextView) findViewById(R.id.totalPounds);
textView.setText(String.valueOf(result)); 

Upvotes: 4

Fergers
Fergers

Reputation: 583

You can use either one of the following:

textView.setText(Integer.toString(result));

or

textView.setText(result + "");

Upvotes: 0

Related Questions