简体   繁体   中英

Verify if EditText is empty Android Studio

I'm kind of stuck in this condition and don't know what to do. I need it to return true or false if users don't insert the value into the EditText . Actually the app crashes and closes.

campoBNow = findViewById(R.id.txtMenorBNow);
campoLucro = findViewById(R.id.txtLucro);

btnClicou.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        //Pega o texto do BuyNow e Lucro e coloca nas variáveis de texto.
        String pegaBNow = campoBNow.getText().toString();
        String pegaLucro = campoLucro.getText().toString();
        String item = spNivel.getSelectedItem().toString(); //Atribui o ComboBox para String...

        //Atribui o valor dos textos convertidos pra float nas variáveis float.
        double bNow = Double.parseDouble(pegaBNow);
        double lDes = Double.parseDouble(pegaLucro);

/*
        Condicional de verificação vazio...
*/

        if(TextUtils.isEmpty(pegaBNow)){
            tv5.setText("DIGITE UM VALOR DE BUY NOW"); //BuyNow vazio, mostra mensagem...
            //Toast.makeText(getApplicationContext(), "DIGITE UM VALOR DE BUY NOW", Toast.LENGTH_LONG ).show();
        } else if(TextUtils.isEmpty(pegaLucro)){
            tv5.setText("DIGITE UM VALOR DE LUCRO"); //Lucro vazio, mostra mensagem...
            //Toast.makeText(getApplicationContext(), "DIGITE UM VALOR DE LUCRO", Toast.LENGTH_LONG ).show();
        } else if(TextUtils.isEmpty(pegaBNow) && TextUtils.isEmpty(pegaLucro)){
            //Toast.makeText(getApplicationContext(), "DIGITE OS VALORES", Toast.LENGTH_LONG ).show();
        }else{
            //Atribui o valor dos textos convertidos pra float nas variáveis float.
            double res = ((bNow - (0.05*bNow)) - lDes); //Calcula o resultado...
            if(res < 0){
                tv5.setText("PROPORÇÃO LUCRO E BUY NOW INCORRETO");
                Toast.makeText(getApplicationContext(), "PROPORÇÃO INCOMPATÍVEL!", Toast.LENGTH_LONG).show();
            }else {
                //Início do IF para o nível da carta...
                if (item == "Ouro") {
                    if (res > 0 && res <= 5000) { //Começar a condicional de comparação de valor.
                        tv5.setText("O RISCO DO TRADE É BAIXO");
                    } else if (res > 5000 && res <= 15000) {
                        tv5.setText("O RISCO DO TRADE É MÉDIO");
                    } else {
                        tv5.setText("O RISCO DO TRADE É ALTO");
                    }


                } else if (item == "Prata") {
                    if (res > 0 && res <= 2000) {
                        tv5.setText("O RISCO DO TRADE É BAIXO");
                    } else if (res > 2000 && res <= 5000) {
                        tv5.setText("O RISCO DO TRADE É MÉDIO");
                    } else {
                        tv5.setText("O RISCO DO TRADE É ALTO");
                    }

                } else { //else para Bronze.
                    if (res > 0 && res <= 1000) {
                        tv5.setText("O RISCO DO TRADE É BAIXO");
                    } else if (res > 1000 && res <= 3000) {
                        tv5.setText("O RISCO DO TRADE É MÉDIO");
                    } else {
                        tv5.setText("O RISCO DO TRADE É ALTO");
                    }

                }
                //Fim do IF para o nível da carta...
            }

            //tv4.setText("COMPRE O JOGADOR POR ATÉ: " + res + " COINS");
            //tv5.setText("RISCO");
        }
    }
});

Move the lines

        double bNow = Double.parseDouble(pegaBNow);
        double lDes = Double.parseDouble(pegaLucro);

To final else part (which works after checking string empty conditions)

You are trying to get double value before checking whether the string is empty or not.

If it is empty, then parseDouble() will throw NumberFormatException which is the reason for app crash.

Use a "for" loop.

private boolean validate(EditText[] fields){
    for(int i = 0; i < fields.length; i++){
        EditText edtTxtName= fields[i];
        if(edtTxtName.getText().toString().length() <= 0){
            return false;
        }
    }
    return true;
}

and use the method like this:

boolean checkField= validate(new EditText[] { campoBNow, campoLucro })

will return true if all fields are non empty.

I think your app crashes because the parseDouble() can't parse an empty statement (if nothing is in the textbox). You will see it in Debug-Mode.

Check value in the Textbox before parseDouble():

if (pegaBNow <= 0 or pegaLucro <= 0) {
   'Emtpy Text -> do sth. but no Parse
} else {
   double bNow = parseDouble(pegaBNow);
   double lDes = parseDouble(pegaLucro);
}

Additionally check also if the user puts a valid Number.

TextUtils.isEmpty(variable_name)应该可以工作,如果应用程序仍然崩溃,您可以使用调试来了解崩溃的原因和位置。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM