All over the net I see examples like edittext.getText().toString()
. I do not see any null check. In docs I do not see any statement that would say that this will never be null.
Still, what does the observations say; does this ever return null?
All over the net I see examples like edittext.getText().toString()
. I do not see any null check. In docs I do not see any statement that would say that this will never be null.
Still, what does the observations say; does this ever return null?
I dont think so it will ever return
null
.But if you want to check whether the returned text is empty or not might I suggest using
TextUtils.isEmpty()
methodEdit:- The documentation doesn't states anything regarding the returned value. And from what I've seen in the source code is that when you initialize a EditText, the default text value is set to
""
. So it will never returnnull
With Android P SDK it is annotated as nullable in the
AppCompatEditText
class so it can return null.And from the docs:
it will return null because when apps runs its empty and it returns null, use .getText.toString inside a button click listener, now when you click button it will get the text which you have entered on editText.
UPDATE:
It does appear as of Jan 18, 2018 this is now possible.
OLD ANSWER:
No,
EditText.getText()
never returnsnull
. One way to verify this is to check the Android source code forEditText.getText()
:EditText.java shows:
Since
EditText extends TextView
, the call tosuper.getText()
must beTextView.getText()
. Now we move on toTextView.getText()
to see what it returns:TextView.java shows:
Now we need to know if
mText
could ever be null.Digging deeper into the TextView.java source we see that
mText
is initialized as an empty string in theTextView
constructor:Once we see that the
EditText
constructor calls theTextView
constructor:we can safely conclude that
EditText.getText()
can never returnnull
, because as soon as anEditText
is constructed,mText
is given a value of an empty string.However, as StinePike pointed out,
EditText.getText()
can possibly cause an NPE if your EditText isnull
when it makes the call togetText()
.try in this way
getText()
will not returnnull
. So there is no chance for NPE in following method. thegetText
will return empty string if there is no string, which is definitely notnull
However the edittext itself can be
null
if not initialized properly, Hence the following will trigger NPE