Check whether the string is null or empty

Asked

Viewed 14,324 times

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 make it to check if the Stock 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();           
}

2 answers

9


I will 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 your length method.

For example:

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

There is also the method isEmpty returning true if the string is empty, and false otherwise. I find more readable for your case.

You can do something like:

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 filled variables and non-null. If you want otherwise, empty variables or null, 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.

  • 1

    @Thanks :) next time edit the post, all help is always welcome ;)

2

When performing this verification in Strings, on Android always use the isEmpty() method of the Textutils class of Android.

TextUtils.isEmpty(suaString);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.