简体   繁体   中英

Preventing android application from crashing

I have a very simple converter app i have created, it works fine if data is entered into one or the other text box, however if i leave them both blank and click one or the other convert buttons it crashes, so i try to include an if statement to handle this but it seemed to ignore that statement and crash anyway. Basically what i want to do if the button is clicked and there is no numbers entered, simply toast a message to the screen asking the user to input data.

public class MainActivity extends Activity {

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

    final EditText txtCentimetersValue = (EditText) findViewById(R.id.txtCentimetersValue);
    final EditText txtInchesValue = (EditText) findViewById(R.id.txtInchesValue);

    Button btnConvert = (Button) findViewById(R.id.btnConvert);
    Button btnConvert2 = (Button) findViewById(R.id.btnConvert2);
    Button btnClear = (Button) findViewById(R.id.btnClear);

    btnClear.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View arg0)
        {
            txtCentimetersValue.setText("");
            txtInchesValue.setText("");
        }
    });

    btnConvert.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View arg0)
        {

                txtInchesValue.setText("");

                double centimeters = Double.valueOf(txtCentimetersValue.getText().toString());
                double inches = centimeters / 0.393700787;

                txtInchesValue.setText(String.valueOf(inches));
        }


    });


    btnConvert2.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View arg0)
        {

                txtCentimetersValue.setText("");

                double inches = Double.valueOf(txtInchesValue.getText().toString());
                double centimeters = inches / 0.393700787;

                txtCentimetersValue.setText(String.valueOf(centimeters));
        }

    });
}

}

so i try to include an if statement to handle this but it seemed to ignore that statement and crash anyway.

I don't see an if statement, perhaps you were trying to use == to compare Strings (which you cannot do in Java) or thought the value was null . Anyway you can simply use isEmpty() :

String value = txtCentimetersValue.getText().toString();
if(!value.isEmpty()) {
    double centimeters = Double.valueOf(value);
    double inches = centimeters / 0.393700787;

    txtInchesValue.setText(String.valueOf(inches));
}

Do something similar for inches to centimeters.

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