-1

It has been a while but I'm back to android development. I am creating a simple stopwatch app.

I have a Timer class and a TextView that i want to update constantly as time is running. I know I can create a thread that will update the TextView but I am not sure of how to do that. Should my Timer extend the thread?

How would the code look to update the textView on a time interval.

This is my Timer class:

public class Timer {

    private double startTime;
    private double endTime;
    private boolean isRunning;

    public Timer() {
        startTime = 0;
        endTime = 0;
        isRunning = false;
    }

    public void reset() {
        isRunning = true;
        startTime = System.currentTimeMillis();
    }

    public double getElapsedTime() {
        if (isRunning)
            endTime = System.currentTimeMillis();
        double timeElapsed = endTime - startTime;
        return timeElapsed;
    }
}

I also found this related question. But I cannot figure out how to make it work. I would appreciate any code that shows how to make the update happen with my code. I didn't include my MainActivity but it's the sample FullScreenActivity.

Community
  • 1
  • 1
Xitcod13
  • 5,949
  • 9
  • 40
  • 81

1 Answers1

1

Try this. It should be more accurate

class Timer extends AsyncTask<Void, String, String>
{

    @Override
    protected String doInBackground(Void... params) {
        long startTime = Calendar.getInstance().getTimeInMillis();
        long nowTime;
        while(true && !isCancelled())
        {
            nowTime = Calendar.getInstance().getTimeInMillis();
            publishProgress((float)((nowTime-startTime)/1000)+"");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onProgressUpdate(String... values) {
        textview.setText(values[0]);
        super.onProgressUpdate(values);
    }

}

dont forget to stop AsyncTask when required by timer.cancel(true);

  • seems like it should work. Im probably missing something. I have created a setTextView() method so i can use a specified textView in Timer class. Yet when i set the textView from MainActivity it doesnt get updated. I guess ill look at it when i wake up. Thanks for your help – Xitcod13 Jun 05 '15 at 13:38
  • I was free at office today so I tried my code. It woks fine on emulator but somehow was not working on my HTC 816G. Hope it helps. It also made system laggy so inserting thread sleep for 100ms inside while loop might help. – Rishabh Singh Bisht Jun 05 '15 at 13:43