Skip to content Skip to sidebar Skip to footer

Android Chronometer: Time Format Issue

Why my chronometer wouldn't stop after I've told it to? I have found out that it seems to be isolated to the tablet I have tested it on (7 inch Galaxy Tab). I have no idea why it w

Solution 1:

I believe what you're experiencing isn't related to "different layout xml files". It seems to be an Android bug, probably this one: Chronometer in Android 4.2.

To check that I've done a couple of tests (with only one layout) on a normal screen size phone (Android 4.2.2) and Samsung Galaxy Tab 7 (Android 4.0.3). I get the following string format of the returned value of chrono.getText().toString()

  1. Android 4.0.3:"mm:ss"
  2. Android 4.2.2:"m:ss"

which corresponds to the reported bug.

Assuming that your Galaxy Tab 7 has Android 4.2 explains why the Chronometer doesn't stop and keeps going ahead: the condition currentTime.equals("00:20") is false because you compare two strings of different format, "m:ss" with "mm:ss".

If my assumption is wrong and it does not regard to the Android version yet there is a solution to handle it.

Answer : I recommend formatting currentTime in a certain manner, e.g. "mm:ss" and then compare the formatted time with "00:20". The following code snippet uses SimpleDateFormat:

chrono.setOnChronometerTickListener(newOnChronometerTickListener() {

        publicvoidonChronometerTick(Chronometer chronometer) {

            String currentTime= chrono.getText().toString();
            Date date = null;
            try {
                date = newSimpleDateFormat("mm:ss").parse(currentTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String newTime = newSimpleDateFormat("mm:ss").format(date);
            ...

Now do the comparison using newTime:

if(newTime.equals("00:20")) {
    // your code
}

Post a Comment for "Android Chronometer: Time Format Issue"