简体   繁体   中英

Android crash when edittext is empty and tap Button

For some reason which I don't know, when I press the button with the EditText empty, the app crashes, but if I put some numbers, it works perfectly. I don't want to add flags like "This field is enabled", I just want to fix the issue.

package com.example.converfuel;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Ticket extends AppCompatActivity {
    private EditText ED1, ED2;
    private TextView TW;
    private Button calcular;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ticket);
        ED1 = (EditText) findViewById(R.id.Num1);
        ED2 = (EditText) findViewById(R.id.Num2);
        TW = (TextView) findViewById(R.id.DIVISION);


        calcular = (Button) findViewById(R.id.calcular);
        calcular.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                float Num1 = Float.parseFloat(ED1.getText().toString());
                float Num2 = Float.parseFloat(ED2.getText().toString());
                float DIV = Num1/Num2;
                TW.setText(DIV+"");

                double val = DIV;
                val = val*100;
                val = Math.round(val);
                val = val / 100;
                mostrar(val);
            }

            private void mostrar(double DIV){
                TW.setText(DIV + "" +" €");
            }
        });
    }
}

You're probably getting NumberFormatException

Check before parsing the values

public static boolean isParsableToFloat(String value) { 
  try {  
    Float.parseFloat(value);  
    return true;
  } catch(NumberFormatException e){  
    return false;  
  }  
}

Then

String valueOfED1 = ED1.getText().toString();
String valueOfED2 = ED2.getText().toString();

if (isParsableToFloat(valueOfED1) && isParsableToFloat(valueOfED2)) {
    float Num1 = Float.parseFloat(valueOfED2);
    float Num2 = Float.parseFloat(valueOfED2);
    //...
} else {
    //...
}

It's Give Error Because Your are Store Value in Num1 & NUM2 Variable and you try to perform DIV = Num1/Num2 this operation that it Gives Error.

if(ED1.getText().length()>0 && ED2.getText().length()>0)
{
     // Your Code
}
else
{
    Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
}

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