Dowemo
0 0 0 0


Question:

I have an EditText and a Button.

I want if an EditText was empty when clicked on my Button. I want to show message as a toast, like "please enter a number".


Best Answer:


The cleanest way to do this is TextUtils.isEmpty(editText.getText())The reason I say this is the cleanest way is because:

  • You avoid pointless conversion between CharSequence and String. Which creates an object. editText.getText() returns Editable, calling toString() creates an additional object which is not good. This method will also never return null in my experience.
  • You get a null and a length check out of that. If you look at the code for TextUtils.isEmpty(), it basically checks if the CharSequence is null and length is zero.
  • It avoids code duplication and the same method can be used with Strings or CharSequence objects and Editable is an implementation of CharSequence.
  • It's provided as part of the Android framework.

If you want to check the length of the trimmed String. Then use:

TextUtils.isEmpty(editText.getText()) 
            && TextUtils.getTrimmedLength(editText.getText()) == 0 

If you want, you can create your own utility method to do this so you don't have to add such a long condition in your code repeatedly.

I would attached an OnFocusChangeListener to your EditText to check the change in value or a TextWatcher or both depending on how critical your requirement is. If your field had focus and lost it, do your validation with the OnFocusChangeListener, if your field has focus and the user is typing and delete the content or the content is too short, use TextWatcher to let them know.




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs