开发者

Force close when all characters are deleted from EditText field

My app is force closing when I delete the last of my characters from the edit text box. e.g. if I put in 456, 6 and 5 cause no problems but deleting 4 leads to the error.

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 (Exc开发者_Go百科eption 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;
}


He broo you have missed else here

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

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

here it will give number format exception because u r parsing null string


Change

if(null==edMiles){

To

if(null == edMiles || edMiles.length() == 0) {

or better use TextUtils.isEmpty(edMiles). When you remove last char from edittext the toString method doesn't return null, it returns ""(empty string) as a result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜