public OnClickListener submitOcl = new OnClickListener() {
public void onClick(View v) {
vibrator.vibrate(30);
//convert from edittext
e = editText1.getText().toString();
e2 = editText2.getText().toString();
num1 = Integer.parseInt(e);
num2 = Integer.parseInt(e2);
// This is my problem!!!Can't set toast about empty fields
if(e.length()==0 && e2.length()==0){
toast = Toast.makeText(getApplicationContext(),
"Fill all fields", Toast.LENGTH_SHORT);
toast.show();
}
//if min more than max value output error
if(num1>num2){
toast = Toast.makeText(getApplicationContext(),
"Error", Toast.LENGTH_SHORT);
toast.show();
}
//output random int value
else if (e.length()>0 && e2.length()>0){
int range = num2 - num1 + 1;
int randomNum = r.nextInt(range) + num1;
tvResult1.setText(""+randomNum);
}
}
};
答案 0 :(得分:0)
你提到了:
//这是我的问题!无法设置关于空字段的祝酒词
if(e.length()== 0&& e2.length()== 0){
而是尝试使用isEmpty()
进行检查。因此,如果你想检查它们是否都是空的,那么:
if(e.isEmpty() && e2.isEmpty()){
}
其他信息:如果您想检查从阅读EditText
后返回的字符串 是否为还是 null
,那么使用if( e!=null && !e.isEmpty()){}
希望这有帮助。
答案 1 :(得分:0)
num1 = Integer.parseInt(e);
num2 = Integer.parseInt(e2);
如果EditText为空,那么这些行会使您的应用崩溃,因为您无法将空String
解析为integer
。
我不知道你的问题是什么,因为你没有告诉我们,但试试这个:
e = editText1.getText().toString();
e2 = editText2.getText().toString();
try {
num1 = Integer.parseInt(e);
num2 = Integer.parseInt(e2);
}catch (Exception f) {
Toast.makeText(getApplicationContext(), "Fill all fields", 0).show();
}
// you don't need this following code because if an EditText is empty,
// it will be caught in the error and the toast above will execute
// but here is how you could also do it anyways:
/*if(e.isEmpty() && e2.isEmpty()){
toast = Toast.makeText(getApplicationContext(), "Fill all fields",
Toast.LENGTH_SHORT);
toast.show();
}*/
答案 2 :(得分:0)
首先,您可以在检查字符串为空或空时使用TextUtils.isEmpty。 其次,您可以使用“或”运算符而不是“和”。 (正如我从你的Toast消息中看到的那样。)
修改:我已经编辑了一些代码。
public OnClickListener submitOcl = new OnClickListener() {
public void onClick(View v) {
vibrator.vibrate(30);
// convert from edittext
e = editText1.getText().toString();
e2 = editText2.getText().toString();
// This is my problem!!!Can't set toast about empty fields
if (TextUtils.isEmpty(e) || TextUtils.isEmpty(e2)) {
Toast.makeText(getApplicationContext(), "Fill all fields", Toast.LENGTH_SHORT).show();
} else {
try {
num1 = Integer.parseInt(e);
num2 = Integer.parseInt(e2);
} catch (Throwable t) {
Toast.makeText(getApplicationContext(), "Only numeric to all fields", Toast.LENGTH_SHORT).show();
return;
}
// if min more than max value output error
if (num1 > num2) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
} else {
// output random int value
int range = num2 - num1 + 1;
int randomNum = r.nextInt(range) + num1;
tvResult1.setText("" + randomNum);
}
}
}
};