Verify that the string is null or empty

6

How do I check if my variable is empty or null?

// Inserção
Nome = tf_Nome.getText().toString();
Tipo = tf_Tipo.getText().toString();
Estoque = Integer.valueOf(tf_Estoque.getText().toString());         
Preco = Double.valueOf(tf_Preco.getText().toString());

I do not know how to do it so that it verifies that the Inventory and Price are blank or null ...

} else if(Nome != null && Tipo != null && **Estoque < 0 && Preco < 0**) {
    Estoque = 0;
    Preco = 0;

    BaseDados.InserirProdutos(Nome, Tipo, Estoque, Preco);
    Limpar();
    Toast.makeText(MainActivity.this, "Produto" +Nome+ " Adicionado com sucesso", Toast.LENGTH_SHORT).show();           
}
    
asked by anonymous 08.10.2014 / 18:46

2 answers

9

I'll assume that the language you use there is Java.

You already know how to compare with null (for example, Nome != null ). If the string is not null, you can see its length through its method length .

For example:

int tamanho = Nome.length() // isso preenche tamanho com o comprimento de Nome.

There is also the isEmpty method that returns true if the string is empty, and false otherwise. I find it more readable for you.

You can do something like this:

public Boolean isStringUsable(string s) {
    return s != null && !s.isEmpty(); // lembre-se de que a comparação
                                      // com nulo sempre deve vir antes,
                                      // para evitar chamar métodos em instâncias nulas
}

The above code is for the case where you want and non-nullable variables. If you want otherwise, empty or void variables, just do the negative of what I did above:

public Boolean isNullOrEmpty(string s) {
    return s == null || s.isEmpty();
}

And pass your strings to this method.

    
08.10.2014 / 19:53
2

When performing this check on Strings, on Android always use the isEmpty () method of the Android TextUtils class.

TextUtils.isEmpty(suaString);
    
14.10.2014 / 14:03