0

OK guys, I am making an android timer app which keeps crashing. I am using a chronometer which resets when it reaches 25 minutes and then starts again. This is being done by a for loop in the start button onclicklistener. In the loop i have another while loop in which i assing a long type variable the value of elapsed time by the statement

// Contents of while loop inside for loop

 while(found==1){
                temp = chrono.getBase() + SystemClock.elapsedRealtime();
                if(temp == 25*60*1000){
                    found--;
                }

I multiplied by 1000 because time is measured in milliseconds? Am i doing this wrong or is it something else. Thanks.

user2018473
  • 215
  • 1
  • 5
  • 8

2 Answers2

2

The while loop probably blocks the main UI thread until the condition found==1 is met. What you probably need is a Timer and a TimerTask. Or, as recommended in this article, you can start a Runnable using a handler to update the chronometer time every 50 or 100 msec. Here is an example (not tested and adapted from the linked article!):

private Handler handler = new Handler();
handler.postDelayed(runnable, 100);

private Runnable runnable = new Runnable() {
   @Override
   public void run() {
      /* do what you need to do */
      boolean isTimerReady=foobar();
      /* and here comes the "trick" */
      if (!isTimerReady) handler.postDelayed(this, 100);
   }
};

This starts foobar() every 100 msec. foobar() should return a boolean value - basically the calculations in your while loop, and update the user interface. Once foobar() returns true, the Runnable is not restarted.

unbehagen
  • 113
  • 5
  • 1 more question plz? For finding time since the stopwatch has been started i am doing it right . Temp is the variable which holds that. – user2018473 Feb 07 '13 at 13:36
  • Depends on the value of ´chrono.getBase()´. I think the correct calculation should be ´elapsedRealtime - initialTime´. – unbehagen Feb 07 '13 at 13:50
  • Sorry I was unable to try this foobar activity? that time. I am trying to implement it now but dont understand how. What I want is for the chronometer to reset after 25 minutes. My question is that what goes into this runnable,the time check? – user2018473 Feb 10 '13 at 05:33
0

You are killing the CPU, and probably never stopping. The likelihood of temp being EXACTLY 25 * 60 * 1000 is very low. Change that "==" check to ">=". Also, use a "boolean" for found: it makes more sense.

David Lavender
  • 8,021
  • 3
  • 35
  • 55