Android 从EditText字段中删除所有字符时强制关闭

Android 从EditText字段中删除所有字符时强制关闭,android,android-edittext,Android,Android Edittext,当我从编辑文本框中删除最后一个字符时,我的应用程序将强制关闭。e、 g.如果我输入456、6和5不会导致问题,但删除4会导致错误 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); setupViews(); } private void setupViews(){ milesBox

当我从编辑文本框中删除最后一个字符时,我的应用程序将强制关闭。e、 g.如果我输入456、6和5不会导致问题,但删除4会导致错误

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    setupViews();

}
private void setupViews(){
    milesBox = (EditText)findViewById(R.id.enter_miles);

    try{
    milesBox.addTextChangedListener(new TextWatcher(){

        @Override
            public void afterTextChanged(Editable s) {

            }
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                    int count) {
                addMiles();
            }
        });
    }catch (Exception e){
        this.showAnswer.setText("TextWatcher error");
        this.milesBox.setText("");
    }



        }// end setupviews()


public void addMiles(){
    try{
        String edMiles = this.milesBox.getText().toString();
        if(null==edMiles){
        this.showAnswer.setText("Please input miles");
        this.milesBox.setText(null);
    }
    double amiles = Double.parseDouble(edMiles);
    setMiles(amiles);
    } 
    catch (Exception e){
        this.showAnswer.setText("Please input miles in numbers");
        this.milesBox.setText(null);
        addMiles();
        //TODO check if this line causes errors
    }
}


public double getMiles() {
    return miles;
}

public void setMiles(double miles) {
    this.miles=miles;
}
改变

或者最好使用
TextUtils.isEmpty(edMiles)
。 当您从edittext中删除最后一个字符时,
toString
方法不会返回null,因此会返回
(空字符串) 你错过了这里的其他东西

if(null==edMiles){
        this.showAnswer.setText("Please input miles");
        this.milesBox.setText(null);
    }
 else{

    double amiles = Double.parseDouble(edMiles);
    setMiles(amiles);
}

在这里,它将给出数字格式异常,因为u r解析空字符串

使用Eclipse中的adb logcat、DDMS或DDMS透视图来检查logcat并查看与“强制关闭”关联的堆栈跟踪。
if(null == edMiles || edMiles.length() == 0) {
if(null==edMiles){
        this.showAnswer.setText("Please input miles");
        this.milesBox.setText(null);
    }
 else{

    double amiles = Double.parseDouble(edMiles);
    setMiles(amiles);
}