I have an EditText
which, whenever I put it in an if statement
with != null
, Android Studio warns me that the value will always be true.
I tried debugging and it advances to the if block
even if I typed nothing in the EditText
.
Here is an example:
EditText emailEditText = (EditText) findViewById(R.id.profile_email_edit_text);
if (emailEditText.getText().toString() != null) { // Android studio warning (Condition 'emailEditText.getText().toString() != null' is always 'true')
Toast.makeText(this, "Not equal to null passed", Toast.LENGTH_SHORT).show();
// toast message appears when I try it
}
Note that if I use .equals("")
instead, no problem happens.
Why does this happen?
emailEditText.getText().toString()
will not return null
. So there is no chance for NPE in following method. the getText
will return empty string if there is no string, which is definitely not null
However the EditText
itself can be null
if not initialized properly!
So you can check weather it is empty or not and do your task! You have many options..
emailEditText.getText().toString().matches("")
emailEditText.getText().toString().trim().equals("")
emailEditText.getText().toString().trim().length() > 0
TextUtils.isEmpty( emailEditText.getText().toString()) // .toString(); is not required as @waqaslam pointed out
EditText#getText
will never return a null
, so the Editable#toString
won't return a null
.
It will return a String
containing the characters that are in the EditText
. If there are no characters, it'll return an empty String
.
Empty String
(""
) isn't a null
.
The interesting thing is, that if you try EditText#setText(null)
, an empty String
will be set.
Your condition should be (!emailEditText.getText().toString().isEmpty())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With