4 回答
TA贡献1831条经验 获得超10个赞
正如另一个答案所解释的那样,您的代码的问题在于,当 EditText 为空时,解析“null”会导致异常。因此,您只需要确保如果内容为空,则只需使用 0(零)值。
你可以试试这个:
public void returnbtn(View view) {
// Initialize insert textView
EditText insertcountBtn = findViewById(R.id.insertPushup);
// Initialize counter textView
TextView givencountBtn = findViewById(R.id.showCount);
int insertcountInt = 0;
int givencountInt = 0;
// get added int stuff from the insert textField
if (!TextUtils.isEmpty(insertcountBtn.getText()) && TextUtils.isDigitsOnly(insertcountBtn.getText())) {
insertcountInt = Integer.parseInt(insertcountBtn.getText().toString());
}
// get string stuff from counter textView
String givencountString = givencountBtn.getText().toString();
if (!TextUtils.isEmpty(givencountString) && TextUtils.isDigitsOnly(givencountString)) {
givencountInt = Integer.parseInt(givencountString);
}
if (givencountInt <= 0 && insertcountInt <= 0){
Total = 0;
} else if (givencountInt > 0 && insertcountInt <= 0) {
Total = givencountInt;
} else if (givencountInt <= 0 && insertcountInt > 0) {
Total = insertcountInt;
} else if (givencountInt > 0 && insertcountInt > 0){
// Add Counter textView and Insert textView to an Int Total
Total = givencountInt + insertcountInt;
}
// Create an Intent to return to the mainActivity.
Intent beginPushup = new Intent(this, MainActivity.class);
// Pass the current number to the push-up Counter activity.
beginPushup.putExtra(TOTAL_DONE, Total);
// Start mainActivity.
startActivity(beginPushup);
}
TextUtils是Android Framework中提供的一个类。
这将检查内容是否为空且是否仅为数字。如果您确定只有数字是您的编辑文本的输入,您显然可以省略数字检查。
TA贡献1785条经验 获得超4个赞
因为当您的 EditText 为空时,它没有数值。
你可以做
Integer.parseInt(insertcountBtn.getText().toString());
当输入为空白时;那里没有 Integer 值,因为什么都没有,所以它会抛出一个 NumberFormatException。
您可以执行以下操作以确保它具有值(失败时默认值为 0):
int insertedcountInt;
try {
insertedCountInt = Integer.parseInt(insertcountBtn.getText().toString());
} catch (NumberFormatException e) {
insertedCountInt = 0;
}
TA贡献1804条经验 获得超7个赞
这里的问题是您正在定义 editText 以仅检查整数:您没有为输入字符串等情况放置条件语句,如果 editText 为空,则它包含字符串。因此,您可能想要放置类似的东西;
String editTextString = String.valueOf(insertcountBtn.getText());
if (editTextString == "") {
//do something
}
或者,
String editTextString = insertcountBtn.getText().toString();
if (editTextString == "") {
//do something
}
添加回答
举报