【问题标题】:Blank field, java causing app crash [duplicate]空白字段,java导致应用程序崩溃[重复]
【发布时间】:2016-02-24 12:43:34
【问题描述】:
当该字段留空时,应用程序会崩溃。我该如何阻止它?
EditText editText = (EditText)findViewById(R.id.editText);
userNumber = Integer.parseInt(editText.getText().toString());
我尝试给它一个 .setError("Don't leave this blank!"),但它似乎没有起作用,应用程序在那里崩溃。
截图:
【问题讨论】:
标签:
java
android
android-studio
crash
【解决方案1】:
尝试从 空或空字符串 到 parseInt 会引发 FormatException。因此,要么将代码包装在 try/catch 中:
try {
userNumber = Integer.parseInt(editText.getText().toString());
}catch(Exception e){
// friendly error to the user: field is incorrect
}
或使用 if 语句确保 editText 不为空:
if(editText.getText().length() > 0){
// your code
}
if 解决方案假设您的 editText 只接受数字(在您的 xml 布局中使用属性 android:inputType="number")。
作为旁注,为了获得良好的实践,请注意将 parseInt 包装在 try/catch 中始终是明智的。
【解决方案2】:
这段代码可以给你一个思路,
String input = editText.getText().toString();
if(input.length() > 0){
try {
int userNumber = Integer.parseInt(input);
// Write your code here
} catch (Exception e) {
Toast.makeText(this, "Enter only a number!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} else{
Toast.makeText(this, "Enter a number!", Toast.LENGTH_SHORT).show();
}
【解决方案3】:
Use this it will help you and remove your crash
EditText editText = (EditText)findViewById(R.id.editText);
if(userNumber.length() > 0)
{
set your error screen is empty
}
else
{
userNumber = Integer.parseInt(editText.getText().toString());
}