當字段留空時,會導致應用程序崩潰。我怎樣才能阻止它?空白字段,導致應用程序崩潰的java
EditText editText = (EditText)findViewById(R.id.editText);
userNumber = Integer.parseInt(editText.getText().toString());
我試着給它一個.setError(「不要離開這個空白!」),但它似乎並沒有做的事,該應用程序崩潰存在。
當字段留空時,會導致應用程序崩潰。我怎樣才能阻止它?空白字段,導致應用程序崩潰的java
EditText editText = (EditText)findViewById(R.id.editText);
userNumber = Integer.parseInt(editText.getText().toString());
我試着給它一個.setError(「不要離開這個空白!」),但它似乎並沒有做的事,該應用程序崩潰存在。
從空或空字符串提出了FormatException
試圖parseInt
。所以,無論是包裝你的代碼在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
}
的,如果解決方案假設您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());
}
發佈異常logcat的請 – Bhargav