What does an EditText.getText() in android return if it is empty?
I've tried null 开发者_JAVA百科and empty string, any other ideas?
No other possibility.
getText
, infact, will never return null. It returns CharSequence
whose contents may be empty.
Instead of doing getText().toString().equals("")
or vice-versa, it may be faster to do getText().length() == 0
If it's empty, this will work:
if(mEditText.getText().toString().equals("")) {
// stuff to run when it's empty
}
Even if it's empty, getText() will still return an Editable, so if you were trying to do this:
if(mEditText.getText().equals("")) {
// stuff
}
It most certainly wasn't working.
You can use TextUtils.isEmpty( mEditText.getText().toString() ). It will return true if its empty/null.
The best way I found to check it is to stock the value in a var like:
String text = mEditText.getText().toString();
and then to use boolean operator isEmpty
like:
if (text.isEmpty){
// stuff
}
After looking at several questions and since it's already possible to get a null I've found the answer to avoid a
method invocation toString may produce NPE
warning all over the place:
String theText = String.valueOf(mEditText.getText());
精彩评论