[英]Checking if EditText is empty crashes application
我正在尝试使用eclipse和android sdk(java)创建一个简单的android应用程序,我有一个EditText框,但有一些限制,但是当EditText框为空时会崩溃,我尝试了很多方法来检查EditText,如果它为空,但是只是想工作..我的代码在下面,为什么当盒子为空时它总是崩溃,应该简单不?
buttonHash.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
switch(v.getId()){
case R.id.hash_button:
TextView msg = (TextView)findViewById(R.id.tell);
info = (EditText)findViewById(R.id.entry);
anss = info.getText().toString();
//String ans = Double.toString(res);
double result = Double.parseDouble(anss);
if (res == result){
msg.setText("Correct");
}else
if (res != result){
msg.setText("Incorrect");
}else
if (info.getText().toString().equals("")){
msg.setText("Empty!");
}
}
}
});
首先检查info.getText()是否为null
if (info.getText() == null || "".equals(info.getText().toString())){
msg.setText("Empty!");
}
请注意,异常可能在这里,而异常是NumberFormatException,因为您正在尝试从“”解析为double。
anss = info.getText().toString();
//String ans = Double.toString(res);
double result = Double.parseDouble(anss);
因此请执行以下操作以避免此问题:
double result = 0;
try{
result = Double.parseDouble(anss);
}catch(NumberFormatException ex)
{
}
您可以使用此代码解决您的问题。
public void onClick(View v) {
if (_text.getText().toString().equals(""))
Toast.makeText(getApplicationContext(), "Empty BOX", 5000).show();
else
Toast.makeText(getApplicationContext(), _text.getText().toString(), 5000).show();
}
就是这样。尝试这个...它将起作用。
试试这个,我刚刚添加了一个警报窗口
public void onClick(View v){if(_text.getText()。toString()。equals(“”)){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Text is empty");
builder.setCancelable(true);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
builder.create().show();
}
else
Toast.makeText(getApplicationContext(), _text.getText().toString(), 5000).show();
}
EditText值永远不会为null。
通过以下方式使用它:
if ((info.getText().toString().trim().getLength() == 0) && ("").equals(info.getText().toString().trim())){
msg.setText("Empty!");
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.