-1

I want to get the integer from the editText and by pressing the button, show the input in textView. The problem is the result is always zero. Thanks in advance for your helps.

    EditText editText = (EditText) findViewById(R.id.editText);
    TextView textView = (TextView) findViewById(R.id.textView);
    Button button = (Button) findViewById(R.id.button);
    try{
    String string = editText.getText().toString();
    int num = Integer.parseInt(string);}
    catch(NumberFormatException numb){
        Toast.makeText(this, "Problem", Toast.LENGTH_SHORT).show();
    }
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String number = String.valueOf(num);
            textView.setText(number);
        }
    });
Mahyar
  • 901
  • 9
  • 13
  • 3
    Possible duplicate of [How to convert a String to an int in Java?](http://stackoverflow.com/questions/5585779/how-to-convert-a-string-to-an-int-in-java) – HaroldSer Mar 22 '17 at 23:19

2 Answers2

1

You need to read EditText value in onClick method to retrieve the updated value

EditText editText = (EditText) findViewById(R.id.editText);
TextView textView = (TextView) findViewById(R.id.textView);
Button button = (Button) findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        try{
            String string = editText.getText().toString();
            int num = Integer.parseInt(string); // retrieve the updated value
            String number = String.valueOf(num);
            textView.setText(number);
        }
        catch(NumberFormatException numb){
            Toast.makeText(this, "Problem", Toast.LENGTH_SHORT).show();
        }
    }
});
lubilis
  • 3,942
  • 4
  • 31
  • 54
0

You have to do all the value look-ups and computation in the listener itself. From what I see here, the string is empty when you initially set "num".

Steve Harris
  • 306
  • 2
  • 4