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我的调试器是正常的。
发布于 2016-02-06 15:30:57
我尝试了您的代码,并在字段的焦点发生变化时调用了validateData()方法。你写的方法很好,除了一件事:
Integer value = Integer.parseInt(txtdate.getText().toString()); 如果用户输入的文本不是整数,则会导致应用程序崩溃。你可以做两件事来防止它
使用android:inputType="textPassword|number"
parseInt捕捉parseInt:尝试{整数值= Integer.parseInt(txtdate.getText().toString());}捕获(异常e) {txtdate.setError(“请输入有效日期(1-31)");}
这样,你的应用程序就不会崩溃。
发布于 2016-02-06 16:16:47
就我个人而言,我会写这样的代码。主要是因为您似乎试图从一个可能为空甚至不是数字的字符串中解析出一个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);
}
} https://stackoverflow.com/questions/32231322
复制相似问题