首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >文本编辑setError

文本编辑setError
EN

Stack Overflow用户
提问于 2015-08-26 23:56:36
回答 2查看 276关注 0票数 0
代码语言:javascript
复制
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我的调试器是正常的。

EN

回答 2

Stack Overflow用户

发布于 2016-02-06 15:30:57

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

代码语言:javascript
复制
Integer value = Integer.parseInt(txtdate.getText().toString()); 

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

  1. 在布局xml文件中,将输入类型设置为number:

使用android:inputType="textPassword|number"

  • Surround - parseInt捕捉parseInt

尝试{整数值= Integer.parseInt(txtdate.getText().toString());}捕获(异常e) {txtdate.setError(“请输入有效日期(1-31)");}

这样,你的应用程序就不会崩溃。

票数 0
EN

Stack Overflow用户

发布于 2016-02-06 16:16:47

就我个人而言,我会写这样的代码。主要是因为您似乎试图从一个可能为空甚至不是数字的字符串中解析出一个int,这会抛出一个异常,而您没有捕捉到这一点。

代码语言:javascript
复制
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);  
    }
}  
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32231322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档