3
respostas

App fecha ao clicar no botão calcular se a EditText estiver vazia

Boa tarde pessoal, estou com um problema no meu aplicativo e não consigo resolver, já pesquisei no google mas não encontrei uma solução,

O aplicativo funciona normalmente, porém se eu deixar alguma EditText vazia, sem nenhum valor, quando eu clico no botão calcular, o aplicativo fecha e apresenta o seguinte erro :

java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
    at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122)
    at java.lang.Float.parseFloat(Float.java:451)
    at br.com.calculadoradividendos.MainActivity$1.onClick(MainActivity.java:58)
    at android.view.View.performClick(View.java:7184)
    at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
    at android.view.View.performClickInternal(View.java:7161)
    at android.view.View.access$3500(View.java:818)
    at android.view.View$PerformClick.run(View.java:27683)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:223)
    at android.app.ActivityThread.main(ActivityThread.java:7562)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
3 respostas
package br.com.calculadoradividendos;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.w3c.dom.Text;

import java.text.DecimalFormat;

import br.com.calculadoradividendos.model.Calculo;

import static android.widget.TextView.*;

public class MainActivity extends AppCompatActivity {

    private float valorDividendo;
    private float valorCota;
    private float valorInvestido;
    private float quantidadeTempo;
    private float TextViewMensal;
    private float TextViewTotal;
    private float TextViewFuturo;
    private Button botaoCalcular;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

        EditText valorDividendo = findViewById(R.id.editTextTextPersonName);
        EditText valorCota = findViewById(R.id.editTextTextPersonName2);
        EditText valorInvestido = findViewById(R.id.editTextTextPersonName3);
        EditText quantidadeTempo = findViewById(R.id.editTextTextPersonName4);
        TextView TextViewMensal = findViewById(R.id.TextViewMensal);
        TextView TextViewTotal = findViewById(R.id.TextViewTotal);
        TextView TextViewFuturo = findViewById(R.id.TextViewFuturo);
        Button botaoCalcular = findViewById(R.id.button);

        botaoCalcular.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float dividendo = (float) 0.0;
                float cota = (float) 0;
                float investimento = (float) 0;
                float tempo = (float) 0;

                dividendo = (float) Float.parseFloat(valorDividendo.getText().toString());
                cota = (float) Float.parseFloat(valorCota.getText().toString());
                investimento = (float) Float.parseFloat(valorInvestido.getText().toString());
                tempo = (float) Float.parseFloat(quantidadeTempo.getText().toString());

                    while (dividendo == 0 || cota == 0 || investimento == 0 || tempo == 0){
                        Toast.makeText(MainActivity.this, "Prencher todos os campos com valor diferente de zero", Toast.LENGTH_SHORT).show();
                        break;
                    }

                    int quantidadeMeses = (int) (tempo * 12);
                    float rendimento = 0;
                    float jurosPorCento = 0;

                    rendimento = (float) ((investimento / cota) * dividendo);

                    jurosPorCento = (float) (dividendo / cota);

                    while (quantidadeMeses > 0) {

                        investimento += (investimento * jurosPorCento);

                        quantidadeMeses = quantidadeMeses - 1;
                    }
                    Calculo calculoTeste = new Calculo(dividendo, cota, investimento, tempo);

                    TextViewMensal.setText(String.format("%.2f", rendimento));
                    TextViewTotal.setText(String.format("%.2f", investimento));

                    float rendimentoFuturo = ((investimento / cota) * dividendo);

                    TextViewFuturo.setText(String.format("%.2f", rendimentoFuturo));

                }
        });
    }
}

Pelo erro, o problema é que o campo está vazio e você tenta fazer uma conversão pra número.

Nesses casos é interessante fazer uma validação se o campo não está vazio. Se estiverem você pode evitar o erro

Bom dia Matheus, li em alguns fóruns que realmente pode ser esse o problema, tentei fazer uma validação mas não obtive sucesso. Tem alguma dica de como posso fazer isso ?