Does EditText.getText() ever returns null?

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


With Android P SDK it is annotated as nullable in the AppCompatEditText class so it can return null.

And from the docs:

Return the text that the view is displaying. If an editable text has not been set yet, this will return null.

@Override
@Nullable
public Editable getText() {
    if (Build.VERSION.SDK_INT >= 28) {
        return super.getText();
    }
    // A bug pre-P makes getText() crash if called before the first setText due to a cast, so
    // retrieve the editable text.
    return super.getEditableText();
}

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