[英]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.