简体   繁体   English

验证 EditText 是否为空 Android Studio

[英]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 .如果用户不将值插入EditText ,我需要它返回truefalse 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. trying to get double value before checking

If it is empty, then parseDouble() will throw NumberFormatException which is the reason for app crash.如果为空,则parseDouble()将抛出NumberFormatException ,这是应用程序崩溃的原因。

Use a "for" loop.使用“for”循环。

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.如果所有字段都不为空,将返回 true。

I think your app crashes because the parseDouble() can't parse an empty statement (if nothing is in the textbox).我认为您的应用程序崩溃是因为 parseDouble() 无法解析空语句(如果文本框中没有任何内容)。 You will see it in Debug-Mode.您将在调试模式下看到它。

Check value in the Textbox before parseDouble():在 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)应该可以工作,如果应用程序仍然崩溃,您可以使用调试来了解崩溃的原因和位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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