Automatic sum of two Edittext to put result in a Textview

Asked

Viewed 160 times

1

I want to take two values out of two EditText and put the result of these two values into one TextView. I made that code but this giving error

editPecaBoas = findViewById(R.id.editPecaBoas);

editPecaRuins = findViewById(R.id.editPecaRuins);


public void sumParts() {

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            int a = Integer.parseInt(editPecaBoas.getText().toString());
            int b = Integer.parseInt(editPecaRuins.getText().toString());

            int i = a + b;

            String t = String.valueOf(i);

            textViewResult.setText(t);
        }
    };

That is the mistake

java.lang.NumberFormatException: For input string: ""

1 answer

2


The mentioned error occurs because you are trying to convert a String empty in a int, you can add a validation, for case the one of EditText is empty consider the value 0. Example:

@Override
public void afterTextChanged(Editable s) {

    String valueStrEditPecaBoas = editPecaBoas.getText().toString();
    String valueStrEditPecaRuins = editPecaRuins.getText().toString();

    int pecasBoas, pecasRuins;

    if(TextUtils.isEmpty(valueStrEditPecaBoas)) {
        pecasBoas = 0;
        editPecaBoas.setText("0");
    } else {
        pecasBoas = Integer.parseInt(valueStrEditPecaBoas);
    }

    if(TextUtils.isEmpty(valueStrEditPecaRuins)) {
        pecasRuins = 0;
        editPecaRuins.setText("0");
    } else {
        pecasRuins = Integer.parseInt(valueStrEditPecaRuins);
    }

    textViewResult.setText(String.valueOf(pecasBoas + pecasRuins));
}

In this example I also made a setText("0") to have a visual return in the field, but it is not necessary to resolve your error.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.