Search code examples
androidandroid-edittextgettext

Android: Check if EditText is Empty when inputType is set on Number/Phone


I have an EditText in android for users to input their AGE. It is set an inputType=phone. I would like to know if there is a way to check if this EditText is null.

I've already looked at this question: Check if EditText is empty. but it does not address the case where inputType=phone.

These, I've checked already and do not work:

(EditText) findViewByID(R.id.age)).getText().toString() == null
(EditText) findViewByID(R.id.age)).getText().toString() == ""
(EditText) findViewByID(R.id.age)).getText().toString().matches("")
(EditText) findViewByID(R.id.age)).getText().toString().equals("")
(EditText) findViewByID(R.id.age)).getText().toString().equals(null)
(EditText) findViewByID(R.id.age)).getText().toString().trim().length() == 0
(EditText) findViewByID(R.id.age)).getText().toString().trim().equals("")
and isEmpty do not check for blank space.

Thank you for your help.


Solution

  • You can check using the TextUtils class like

    TextUtils.isEmpty(ed_text);
    

    or you can check like this:

    EditText ed = (EditText) findViewById(R.id.age);
    
    String ed_text = ed.getText().toString().trim();
    
    if(ed_text.isEmpty() || ed_text.length() == 0 || ed_text.equals("") || ed_text == null)
    {
        //EditText is empty
    }
    else
    {
        //EditText is not empty
    }