user2992655 user2992655 - 3 months ago 11
Java Question

NumberFormatException while converting string to Integer

I'm getting integers of two EditText and on one of them textWatch is applied, multiplying them and setting text to another EditText. it normally works fine but when one of edit field become empty while hitting backspace app crashes.

protected final TextWatcher getValueWatcher = new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
int qty = Integer.parseInt(s.toString());
int unitPrice = Integer.parseInt(unitPriceEdit.getText().toString());
if (s.length() > 0)
totalPriceEdit.setText(String.valueOf(qty * unitPrice));
}
public void afterTextChanged(Editable s) {
}
};


Logcat

java.lang.NumberFormatException: Invalid int: "" at
java.lang.Integer.invalidInt(Integer.java:138) at
java.lang.Integer.parseInt(Integer.java:358) at
java.lang.Integer.parseInt(Integer.java:334) at
com.example.fani.project.MainActivity$2.onTextChanged(MainActivity.java:90)
at android.widget.TextView.sendOnTextChanged(TextView.java:7679) at
android.widget.TextView.handleTextChanged(TextView.java:7739)

Lal Lal
Answer

Replace your code as below

protected final TextWatcher getValueWatcher = new TextWatcher() {
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    public void onTextChanged(CharSequence s, int start, int before, int count) {
      if (s.length() > 0){
        int qty = Integer.parseInt(s.toString());
        int unitPrice = Integer.parseInt(unitPriceEdit.getText().toString());
        totalPriceEdit.setText(String.valueOf(qty * unitPrice));
      }
    }
    public void afterTextChanged(Editable s) {
    }
};

Check the length of your string before parsing it..