Does EditText.getText() ever returns 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?
Solution 1:
getText()
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
getText().toString();
However the edittext itself can be null
if not initialized properly, Hence the following will trigger NPE
editText.getText().toString();
Solution 2:
UPDATE:
It does appear as of Jan 18, 2018 this is now possible.
OLD ANSWER:
No, EditText.getText()
never returns null
. One way to verify this is to check the Android source code for EditText.getText()
:
EditText.java shows:
public Editable getText() {
return (Editable) super.getText();
}
Since EditText extends TextView
, the call to super.getText()
must be TextView.getText()
. Now we move on to TextView.getText()
to see what it returns:
TextView.java shows:
public CharSequence getText() {
return mText;
}
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 the TextView
constructor:
public TextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mText = "";
…
}
Once we see that the EditText
constructor calls the TextView
constructor:
public EditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
we can safely conclude that EditText.getText()
can never return null
, because as soon as an EditText
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 is null
when it makes the call to getText()
.