空白字段,java 导致应用程序崩溃
Blank field, java causing app crash
当该字段留空时,它会使应用程序崩溃。我怎样才能阻止它?
EditText editText = (EditText)findViewById(R.id.editText);
userNumber = Integer.parseInt(editText.getText().toString());
我试着给它一个 .setError("Don't leave this blank!"),但它似乎没有做那件事,应用程序在那里崩溃了。
截图:
尝试从 空字符串或空字符串 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 内总是明智的。
这段代码可以给你一个思路,
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();
}
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());
}
当该字段留空时,它会使应用程序崩溃。我怎样才能阻止它?
EditText editText = (EditText)findViewById(R.id.editText);
userNumber = Integer.parseInt(editText.getText().toString());
我试着给它一个 .setError("Don't leave this blank!"),但它似乎没有做那件事,应用程序在那里崩溃了。
截图:
尝试从 空字符串或空字符串 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 内总是明智的。
这段代码可以给你一个思路,
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();
}
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());
}