我尝试过null和空字符串,还有其他想法吗?
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());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.