0

I'm trying to multiply the value of my chronometer or just try to get the value to be a string.

Every time I try to make it a string and use toast.show() to view it, my application crashes. I can get the value of my EditText to show up but I can't seem to get my chronometer to work. Both the strings time and fin make it crash. Here's the code:

String hour = String.valueOf(mText.getText());
String time = String.valueOf(mChronometer.getBase() - stoppedMilliseconds);
int h = java.lang.Integer.parseInt(hour) / 60;
int t = java.lang.Integer.parseInt(time) * 1000 / 60;
int mm = h * t;
mon.setText(Integer.toString(mm));
String fin = "" + mm;


Toast.makeText(PoopActivity.this,
        "Money made: " + fin, Toast.LENGTH_LONG).show();
prolink007
  • 33,872
  • 24
  • 117
  • 185
Mike
  • 1
  • 2

1 Answers1

0

There are several defects obscuring the function of this code.

  • time is always negative. Swap the subtraction arguments.
  • When converting hour from hours to minutes, multiply rather than divide by 60.
  • When converting time from milliseconds to minutes, divide rather than multiply by 1000.
  • Computation of mm yields a quantity in minutes squared. This can hardly have any meaning.
  • Use getApplicationContext instead of PoopActivity. Some application other than PoopActivity may be running.
  • There is no exception handling. For all we know, mon may be null and the setText throw an exception. Wrap your code in a try - finally block:

String fin = "";

try
{
    // most of your code goes here

    mon.setText(Integer.toString(mm));
    String fin += mm;
}
catch (Exception e)
{
    // display the exception here if so inclined
}
finally
{
    Toast.makeText(PoopActivity.this,
    "Money made: " + fin, Toast.LENGTH_LONG).show();
}

However, fin is a string containing a negative number just fine.

Jirka Hanika
  • 13,301
  • 3
  • 46
  • 75