K.Mir K.Mir - 1 month ago 6
Android Question

How to stop the app crashing when String is empty

The app crash when there is no text !
I don't have what 'if' to put to fix that !
Thanks you

enter TextView TotalTextView;
EditText EnterPercentage;
EditText EnterPrice;

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


TotalTextView = (TextView) findViewById(R.id.TotalTextView);
EnterPercentage = (EditText) findViewById(R.id.EnterPercentage);
EnterPrice = (EditText) findViewById(R.id.EnterPrice);
Button CalcBtn = (Button) findViewById(R.id.CalcBtn);


CalcBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {

float percentage = Float.parseFloat(EnterPercentage.getText().toString());
float prix = Float.parseFloat(EnterPrice.getText().toString());
float dec = percentage / 100;
float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());

TotalTextView.setText(String.format("%.2f", total));


}
});


Thank for your answer, I am a begineer so... Thanks !

if (EnterPercentage.getText().equals("")) {

float percentage = Float.parseFloat(EnterPercentage.getText().toString());
float prix = Float.parseFloat(EnterPrice.getText().toString());
float dec = percentage / 100;
float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());
TotalTextView.setText(String.format("%.2f", total));


} else {


}

the button don't do anything but the app doesn't crash

Tim Tim
Answer

We check the length of the String... when it's 0 then we do nothing. When the String > 0 your code is running.

Like:

            if (EnterPercentage.getText().toString().length() == 0 || EnterPrice.getText().toString().length() == 0 ) {
                //Textfields are empty.
            } else {
                //Textfield is full
                float percentage = Float.parseFloat(EnterPercentage.getText().toString());
                float prix = Float.parseFloat(EnterPrice.getText().toString());
                float dec = percentage / 100;
                float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());
                TotalTextView.setText(String.format("%.2f", total));
            }
Comments