Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the value of an EditText (not null) always true?

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?

like image 484
Android Admirer Avatar asked Jan 04 '23 17:01

Android Admirer


2 Answers

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
like image 54
Charuක Avatar answered Jan 12 '23 01:01

Charuක


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())

like image 31
xenteros Avatar answered Jan 11 '23 23:01

xenteros