1

I am making an app in android studio, and I want to be able to display the amount of time left until a certain time in the day. For some reason I can't seem to get my code to work; when I run my code does anyone know what I am doing wrong?

mChronometer = (Chronometer) findViewById(R.id.end_chronometer);
mChronometer.setCountDown(true);
mChronometer.setBase(convertToDate(timeStr));

...

private long convertToDate(String str)
{
    try
    {
        DateFormat mDateTimeFormat = new SimpleDateFormat("HH:MM");

        Date date = mDateTimeFormat.parse(str);
    } catch (java.text.ParseException e)
    {
        e.printStackTrace();
    }
    return SystemClock.elapsedRealtime();
}
  • Please explain, **in detail**, what "I can't seem to get my code to work" means. Note that you are setting this to count down from 0 (`setBase()` with a value of `SystemClock.elapsedRealtime()`). – CommonsWare Mar 15 '17 at 17:07
  • My Chronometer always displayed a value of zero, so how would I set the time I am counting down until? – Guillermo W Mar 15 '17 at 17:21
  • Call `setBase()` with a time in the future, IIRC. So, add some number of milliseconds to `SystemClock.elapsedRealtime()`, and use that value for `setBase()`. – CommonsWare Mar 15 '17 at 17:33
  • Ok, but what if my countdown timer isn't based on the number of seconds left until an event, but more specifically I know my timer wants to countdown to 1:15 pm, and I'm not sure when I'm going to start my timer. Do I just find the difference in time between the two times then add that to elapsedRealTime() ? – Guillermo W Mar 16 '17 at 00:23
  • Okay, I think I got it working, Thank you so much for your help! – Guillermo W Mar 16 '17 at 02:13

1 Answers1

0

you can use CountDownTimer.

 new CountDownTimer((hourOfDay * 60 + minute1) * 60 * 1000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                SimpleDateFormat mTimeFormat = new SimpleDateFormat("mm:ss");
                mTvRemainTime.setText(mTimeFormat.format(new Date(millisUntilFinished)));
            }

            @Override
            public void onFinish() {
                mTvRemainTime.setText("stop");
            }
        }.start();
Benchur Wong
  • 2,377
  • 2
  • 9
  • 13