简体   繁体   中英

Crash in my Android App: OnClickListener

I'm new to android and trying to create a simple program that adds three inputs together and then prints the output to an EditText. Whenever I hit the button I'm getting a crash in line 63 (the last line I posted below) of my code... I think it could be due to a null object or something like that. I'm 99% sure all of my variables and everything else are declared correctly. Anyways, here's my code for onClick method and if anyone can figure out what's causing the crash I'd be much obliged.

Button solve = (Button) findViewById(R.id.solve);

solve.setOnClickListener(new OnClickListener() {

    public void onClick(View arg0) {

        if  ((a.getText().length() == 0)
            || (" ".equals(a.getText().toString()))
            || (" ".equals(b.getText().toString()))
            || (" ".equals(c.getText().toString()))
            || (b.getText().length() == 0)
            || (c.getText().length() == 0)) {
Toast.makeText(getApplicationContext(), "Some of your inputs are empty.",  Toast.LENGTH_SHORT).show();

        } else {

            double sol = new Double(a.getText().toString())
            + new Double(b.getText().toString())
            + new Double(c.getText().toString());
            res1.setText(Double.toString(sol)); //line that is causing the crash

You can try to use Double.Parse ...

and

res1.setText(String.valueOf(sol));

You are converting String values to Double in wrong way, see you can do it in following two ways,

  1. use Double.parseDouble()

     double sol = new Double.parseDouble((a.getText().toString().trim()); // also don't forget to use trim() method to remove white spaces 
  2. use new Double( value ).doubleValue()

     double sol = new Double(a.getText().toString().trim()).doubleValue(); 

Now coming to set this sol variable's value to EditText try following way,

  1. res1.setText((String)sol));
  2. res1.setText(String.valueOf(sol));
  3. res1.setText( sol + "" );

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