Mahyar Mohammadi Mahyar Mohammadi -4 years ago 220
Android Question

Android: converting Int to String and viceversa (Using try and catch in listener)

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);
}
});

Answer Source

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();
        }
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download