将字符串转换为Integer时的NumberFormatException

时间:2015-08-07 10:43:10

标签: java android

我得到两个EditText的整数,并在其中一个上应用textWatch,将它们相乘并将文本设置为另一个EditText。它通常工作正常但当其中一个编辑字段变空时,同时遇到退格应用程序崩溃。

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) 

3 个答案:

答案 0 :(得分:2)

将代码替换为如下

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

在解析之前检查字符串的长度..

答案 1 :(得分:1)

修改你的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));
    }
}

答案 2 :(得分:0)

由于var owl; $(document).ready(function() { owl = $("#owl-demo"); owl.owlCarousel({ navigation: false, slideSpeed: 300, paginationSpeed: 400, singleItem: true, afterInit: afterOWLinit }); function afterOWLinit() { ... } }); 而发生

空指针错误 在您的代码中更改此内容。

s.length > 0

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