开发者

How to check if EditText has a value in Android / Java [duplicate]

This question already has answers here: How do I check if my EditText fields are empty? [closed] (30 answers) Closed 9 years ago.

This should be simple, but I have tried if statements checking for null va开发者_StackOverflow社区lues and also ones checking the .length of it:

EditText marketValLow = (EditText) findViewById(R.id.marketValLow);
EditText marketValHigh = (EditText) findViewById(R.id.marketValHigh);
if (marketValLow.getText().length() != 0 && marketValHigh.getText().length() != 0) {
    Intent intent = new Intent();
    intent.setClass(v.getContext(), CurrentlyOwe.class);
    startActivity(intent);
} else {
    Toast.makeText(CurrentMarketValue.this, "You need to enter a high AND low.", Toast.LENGTH_SHORT);
}

But it doesn't detect nothing was entered. Any ideas?


Please compare string value not with == but equals() :

String yourString = ;
if (marketValHigh.getText().toString().equals(""))
{
    // This should work!
}


This will check if the edit text is empty or not:

if (marketValLow.getText().toString().trim().equals(""))
{
}


Rather what you can check is like:

String text = mSearchText.getText().toString();

if (!TextUtils.isEmpty( mSearchText.getText().trim())) {
    // your code
}


Maybe like this?

String value = editText.getText().toString();
if (value == "")
{
    // your code here
}


If it stops progression to the next activity but doesn't show the toast there must be something wrong in your else statement. Have you read the Dev Guide article on Toast notifications? It is under User Interface -> Notifying the User -> Creating Toast Notifications.


Validation is somewhat tedious. Maybe I can help you in a more generic manner. I have written a basic framework to validate fields in Android.

It is totally free, and you can do whatever you like with it.


write a simple function inside a class:

    public static boolean isEditTextEmpty( EditText et){
      String s = et.getText().toString();
      return s.equals("");  // really empty.          
   }

    public static boolean isEditTextInvisible( EditText et){
      String s = et.getText().toString();
      return s.trim().equals("");  // might have only spaces...           
   }

OR... with positive Logic:

    public static boolean hasContentEditText( EditText et){
      String s = et.getText().toString();
      return s != null; // spaces will count.             
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜