Search code examples
androidtextviewandroid-edittext

Handle Change of TextView according to EditText with Empty value


I am using TextChangedListener on a EditText called "deviseValue" and make operations with it to show other values in sellValue and buyValue which are two TextViews, as follows :

deviseValue.addTextChangedListener(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) {
            Double dDeviseValue = Double.valueOf(deviseValue.getText().toString());
            Double sellResult = dDeviseValue*dSellValue;
            Double buyResult = dDeviseValue*dBuyValue;
            sellValue.setText(sellResult.toString());
            buyValue.setText(buyResult.toString());
        }
    });

Everything works fine, BUT, when I remove all value of deviseValue (i.e : EMPTY) .. my app crashes !!

How to handle this situation so when user remove all value, deviseValue become automatically > 1. ?


Solution

  • App crashed because you try to convert a string value from a edittext to the double value. But when you cleared your edittext deviseValue.getText().toString() is ""(empty). That's why you got NumberFormatException.

    Try to check deviseValue.getText().toString() before convert it to the double. For example:

    String dDeviseText = etEmail.getText().toString();
    Double dDeviseValue = Double.valueOf(dDeviseText.isEmpty() ? "1" : dDeviseText);
    

    And you should prevent input not a numbers characters for this edittext.