【问题标题】:textedit setError文本编辑集错误
【发布时间】:2015-08-26 15:56:35
【问题描述】:
public void validateData() {  
    EditText txtdate = (EditText) findViewById(R.id.txtdate);  
    Integer value = Integer.parseInt(txtdate.getText().toString());  
    if (txtdate.getText().toString().length()==0)  
        txtdate.setError("field cannot be empty please enter the correct values");  
    else if (value>31 ||value<1)  
        txtdate.setError("Date must be from 1 to 31");  
    else {  
        Intent intentuserinput=new Intent(getApplicationContext(),UserEpenses.class);  
        startActivity(intentuserinput);  
    }
}  

我的这段代码只有在我只有/任何一个“if”和else但不能同时使用两个if时才有效。我在模拟器上得到的消息是myApp stopped working我的调试器是正常的。

【问题讨论】:

  • validateData() 方法何时被调用?
  • “myApp 停止工作”并不意味着您的应用程序崩溃了。日志猫说什么?

标签: android android-edittext parseint


【解决方案1】:

我尝试了您的代码并在字段焦点发生更改时调用了validateData() 方法。你写的方法很好,除了一件事:

Integer value = Integer.parseInt(txtdate.getText().toString()); 

如果用户输入的文本不是整数,会导致应用崩溃。你可以做两件事来防止它

  1. 在您的布局 xml 文件中,将输入类型设为数字:

    android:inputType="textPassword|number"
    
  2. 用 try-catch 包围parseInt

    try {    
        Integer value = Integer.parseInt(txtdate.getText().toString());  
    } Catch (Exception e) {
        txtdate.setError("Please enter a valid date (1-31)");
    }
    

这样,您的应用就不会崩溃。

【讨论】:

    【解决方案2】:

    就个人而言,我会编写类似这样的代码。主要是因为您似乎试图从一个可能为空甚至不是数字的字符串中解析一个 int,这会引发异常,而您没有抓住它。

    public void validateData() {  
        String errorMsg = "";
        EditText txtdate = (EditText) findViewById(R.id.txtdate);  
        String s = txtdate.getText().toString();  
    
        if (s.length() == 0) {  
            errorMsg = "field cannot be empty please enter the correct values";
        }
    
        Integer value = null;
    
        try {    
            value = Integer.parseInt(s);  
        } catch (NumberFormatException e) {
            e.printStackTrace();
            errorMsg = "Please enter a valid date (1-31)";
        }
    
        if (value == null || value > 31 || value < 1) {  
            errorMsg = "Date must be from 1 to 31";
        }  
    
        if (!errorMsg.isEmpty()) {
            txtdate.setError(errorMsg);
        } else {
            Intent intentuserinput=new Intent(getApplicationContext(),UserEpenses.class);  
            startActivity(intentuserinput);  
        }
    }  
    

    【讨论】:

      猜你喜欢
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 2016-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-22
      相关资源
      最近更新 更多