owenoliver1
owenoliver1

Reputation: 77

When no data is entered the program crashes with data it is fine (android)

The issue i'm having is that when I enter no data at all or if there is only data in one of the input boxes the program crashes but if there is any data in both boxes the program works fine so how do I stop it from sending data if nothing is entered. The error says it can parse a double of value ""

    calculate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            distanceTraveled = Double.parseDouble(distance.getText().toString());
            fuelUsed = Double.parseDouble(fuel.getText().toString());
            part1 = fuelUsed / 4.55;
            mpg = distanceTraveled / part1;
            total.setText(String.format("%.2f", mpg));
        }
    });

Upvotes: 1

Views: 104

Answers (2)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

Chnage EditView for empty or null before making calculation :

alculate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
          if(distance.getText().toString().length() > 0){

            distanceTraveled = Double.parseDouble(distance.getText().toString());
        }
        else{
              distanceTraveled=0; // put default value here
          }
        if(fuel.getText().toString().length() > 0){  
               fuelUsed = Double.parseDouble(fuel.getText().toString());
          }
          else{
               fuelUsed=0;// put default value here

           }
            part1 = fuelUsed / 4.55;
            mpg = distanceTraveled / part1;
            total.setText(String.format("%.2f", mpg));
        }
    });

Upvotes: 1

Marcin S.
Marcin S.

Reputation: 11191

Before you attempt to retrieve the values from input fields check whether they are empty or not:

if (distance.getText() != null && fuel.getText() != null ) {
    distanceTraveled = Double.parseDouble(distance.getText().toString());
    fuelUsed = Double.parseDouble(fuel.getText().toString());
    part1 = fuelUsed / 4.55;
    mpg = distanceTraveled / part1;
    total.setText(String.format("%.2f", mpg));
} else {
    // You can display a message here for example Toast message that fields cannnot be empty
{

Upvotes: 0

Related Questions