简体   繁体   中英

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) 

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..

Modify your onTextChanged():

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

null pointer error occurs due to s.length > 0 Change this in your code.

 if (s.length() > 0)
    totalPriceEdit.setText(String.valueOf(qty * unitPrice));
 }

TO

if(s != null){

   if (s.length() > 0)
    totalPriceEdit.setText(String.valueOf(qty * unitPrice));
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM