2012-03-10 95 views
0

我想创建一个简单的android应用程序使用eclipse和android sdk(java)我有一个EditText框有一些限制,但它在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!"); 
      } 
     }  
    } 
}); 
+0

你为什么checki在使用它之后查看字符串是否为空?从LogCat中可以看出哪一行导致它崩溃? – PearsonArtPhoto 2012-03-10 03:35:39

+0

logcat在哪里? – 2012-03-10 03:35:42

+0

花花公子的最后一位崩溃我只是想显示消息“空”,如果textview是空的 – Tacit 2012-03-10 03:37:56

回答

0

您可以使用此代码来解决你的问题。

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(); 

     } 

多数民众赞成它..试试这个......它会奏效。

0

为info.getText()首先检查为空

if (info.getText() == null || "".equals(info.getText().toString())){ 
      msg.setText("Empty!"); 
      } 
0

请注意例外可能是在这里,而例外的是NumberFormatException的,因为你正试图从分析“”双。

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) 
{ 
} 
0

试试这个我刚才添加一个警告窗口

公共无效的onClick(视图v){ 如果(_text.getText()。的toString()。等于( “”)){

    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(); 

     } 
0

的EditText值永远不会为空..

使用它在下列方式:

if ((info.getText().toString().trim().getLength() == 0) && ("").equals(info.getText().toString().trim())){ 
      msg.setText("Empty!"); 
      } 
     }