How to test if an EditText is empty?

4

I would like to know how do I test if an EditText is empty or populated in Android. For example, I want to make an app that will perform a registration, but there are fields that can not be empty so I would like to know how to do this test, in case, if there was an empty field, it would return a message saying that the fields do not can be left blank.

    
asked by anonymous 12.09.2015 / 02:20

7 answers

4
if(meuEditText.getText().length() == 0){//como o tamanho é zero é nulla aresposta

       meuEditText.setError("Campo vazio");

}else if (meuEditText.getText().length() < 5){

      meuEditText.setError("Minimo 5 letras");

}

Next post some code, post your attempt,

    
12.09.2015 / 03:01
4
if (meuEditText.getText().toString().trim().equals("")) {
    ....

Note that getText() never returns the value null , at worst it returns empty, ie "".

Optionally you can test length() == 0 or isEmpty() (this last case from the API level 9).

    
12.09.2015 / 03:10
2

So you can check this way by creating the following function, which will check if you have white space and if the string size is less than 1.

private boolean isEmpty(EditText etText) {
        String text = etText.getText().toString().trim();
        if (text.length()<1)
            return true;
        return false;
}

I answered in this question also here .

    
08.08.2016 / 19:36
2

You can test this way with equals("")

Ex:

@Override
    public void onClick(View view) {
        if (edtAltura.getText().toString().equals("")) {
            Toast.makeText(getApplicationContext(), "Campo Altura está vazio!", Toast.LENGTH_SHORT).show();
            edtAltura.requestFocus();
        } else if (edtPeso.getText().toString().equals("")) {
            Toast.makeText(getApplicationContext(), "Campo Altura está vazio!", Toast.LENGTH_SHORT).show();
            edtPeso.requestFocus();
        } else {
    }
}
    
20.12.2016 / 03:19
0
if(editText.getText().toString().matches("")){
 .....
}

The matches() method tells whether or not the given string matches a given regular expression.

    
12.09.2015 / 17:05
0

You can use the following:

if (meuEditText.getText().toString().isEmpty()) {
   //faça tal...
}
    
08.08.2016 / 20:22
0

The most efficient way is to use the TextUtils class as follows:

TextUtils.isEmpty(nome_editText.getText().toString());

it checks for example if 2 blank spaces have been inserted. What does not happen if you get the length of the inserted string in editText .

    
17.09.2015 / 15:27