views:

5582

answers:

2

I have a Chronometer widget in my Android app. I was wondering how to get the time from it. I tried getText, getFormat, getBase, etc, but none of them work. This is probably a easy question, but I could not find it on Google.
Thanks, Isaac Waller

Example code snippet:

Chronometer t = (Chronometer)findViewById(R.id.toptime);
long time = SystemClock.elapsedRealtime()-t.getBase();
Log.d(null,"Was: "+time); //time is not the proper time for some reason - it is a random number between 0 and 50
t.setBase(SystemClock.elapsedRealtime());
t.start();
+6  A: 
nyenyec
Hello,thank you, but I cannot get it to work - I always get a (seemingly) random number between 1 and 50 about when I try.Thanks, Isaac
Isaac Waller
It should be an easy thing to fix. Can you post a code snippet?
nyenyec
I posted a code snippet - thanks.
Isaac Waller
+2  A: 

I found this example really useful, thanks nyenyec!

Here's my two cents on how to turn it into a real stopwatch function, without subclassing Chronometer. Just change the mStartListener method to parse the text from mChronometer (it's derived from TextView after all), calculate milliseconds, and use setBase() to readjust the base time to that amount of time in the past:

  View.OnClickListener mStartListener = new OnClickListener() {
    public void onClick(View v) {

      int stoppedMilliseconds = 0;

      String chronoText = mChronometer.getText().toString();
      String array[] = chronoText.split(":");
      if (array.length == 2) {
        stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 1000
            + Integer.parseInt(array[1]) * 1000;
      } else if (array.length == 3) {
        stoppedMilliseconds = Integer.parseInt(array[0]) * 60 * 60 * 1000 
            + Integer.parseInt(array[1]) * 60 * 1000
            + Integer.parseInt(array[2]) * 1000;
      }

      mChronometer.setBase(SystemClock.elapsedRealtime() - stoppedMilliseconds);
      mChronometer.start();
    }
  };
Hakayati
Thanks for you answer. I've used to solve this: http://stackoverflow.com/questions/2324701/android-chronometer-as-a-persistent-stopwatch-how-to-set-starting-time-what-is/2333564#2333564
Macarse
Any ideea how to fix this: http://stackoverflow.com/questions/3811005/android-chronometer-doesnt-start ?
Alin