3

I am using countdown timer in my application where i need to display upcoming date in days hours minutes and seconds left.I got the days,hours,minutes and seconds but when i set it to text view the countdown doesn't start.The below is my code.

Date date = new Date(2013,Integer.parseInt(datess.get(k).split("-")[1])-1,Integer.parseInt(datess.get(k).split("-")[0]),hours,mins,secs);  
     long dtMili = System.currentTimeMillis();  
     Date dateNow = new Date(dtMili);  
      remain = date.getTime() - dateNow.getTime();


MyCount counter = new MyCount(remain,1000);
            counter.start();

public class MyCount extends CountDownTimer{
    public MyCount(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        }



    @Override
    public void onFinish() {
        // TODO Auto-generated method stub

        tv3.setText("done");
    }

    @Override
    public void onTick(long millisUntilFinished) {
        // TODO Auto-generated method stub


        tv3.setText(timeCalculate(millisUntilFinished/1000) + " Countdown");

    }
}

 public String timeCalculate(long ttime)   
   {  
     long  daysuuu,hoursuuu, minutesuuu, secondsuuu;  
     String daysT = "", restT = "";  



     daysuuu = (Math.round(ttime) / 86400);  
     hoursuuu = (Math.round(ttime) / 3600) - (daysuuu * 24);  
     minutesuuu = (Math.round(ttime) / 60) - (daysuuu * 1440) - (hoursuuu * 60);  
     secondsuuu = Math.round(ttime) % 60;  


     if(daysuuu==1) daysT = String.format("%d day ", daysuuu);  
     if(daysuuu>1) daysT = String.format("%d days ", daysuuu);  

     restT = String.format("%02d:%02d:%02d", hoursuuu, minutesuuu, secondsuuu);  

     return daysT + restT;  
   }  

This is the output

enter image description here

Why is the countdown not started? Any Suggestions are appreciated.

hemanth kumar
  • 3,068
  • 10
  • 41
  • 64
  • if the counter doesn't start, you probably forgot to call .start() on the timer – Entreco Dec 12 '12 at 06:11
  • Have you called `start()`? Other than that it is impossible to help you without seeing all of the relevant code. – Sam Dec 12 '12 at 06:12
  • i have called start method i forgot to put that piece of code here. – hemanth kumar Dec 12 '12 at 06:14
  • Does your app crash? Post your entire MyCount class so we can see what is happening. Also consider using SimpleDateFormat or the Joda Time library to convert your milliseconds into a readable String. – Sam Dec 12 '12 at 06:25
  • @Sam App doesnt crash. It displays the string correctly.I have edited the code too.please go through it. – hemanth kumar Dec 12 '12 at 06:30
  • I assumed that your were recalculating `days`, `hours`, etc in code that you weren't showing, but I now believe you aren't doing this at all. – Sam Dec 12 '12 at 06:43
  • If you are still getting `693` days then `date` is current problem... What value does return `datess.get(k)`? Is it in `dd/mm` format like you expect or possibly `mm/dd`? And what are the values for `hours`, `minutes`, and `seconds`? – Sam Dec 19 '12 at 17:58

4 Answers4

6

You are not using the millisUntilFinished parameter to update your time in timeCalculate(). Start with:

@Override
public void onTick(long millisUntilFinished) {
    tv3.setText(millisUntilFinished + " Countdown");
}

Once you've confirmed that the timer is working, you'll need a method to convert millisUntilFinished into a human readable String.

The classes related to dates and times in Java are unnecessarily difficult to work with and have some obscure errors. (For instance much of the Date class is deprecated, but the recommended Calendar class still relies on Date heavily...) The 3rd party library Joda Time is a popular replacement.


Addition

the output is not what i expected

25,000 to 700 days in the future is not what I would expect either, date appears to be wrong. As gabriel points out in another answer to this question the year value is calculated from 1900. Though something else is still wrong since 25,000 days is less than 70 years in the future...
However this constructor is deprecated and shouldn't be used, Calendar is the recommended class. I wrote a quick demo using Calendar for you.

But understand that CountDownTimer itself has a couple fundamental flaws:

  • Every time onTick() is called CDT adds a few milliseconds to the overall time, I noticed that it can easily add 7 and half minutes every day.
  • Because of the first error the last onTick() might no be called. When counting down from 5, I typically see "5, 4, 3, 2, <long pause>" then onFinished() displays "0"...

I rewrote CDT in a previous question: android CountDownTimer - additional milliseconds delay between ticks.

Community
  • 1
  • 1
Sam
  • 86,580
  • 20
  • 181
  • 179
  • i have passed the parameter millisUntilFinished in timeCalculate().But still the result is same. – hemanth kumar Dec 12 '12 at 07:04
  • yes it works this way, public void onTick(long millisUntilFinished) { tv3.setText(millisUntilFinished + " Countdown"); } but when i put tv3.setText(timeCalculate(millisUntilFinished) + " Countdown"); it doesnt. – hemanth kumar Dec 12 '12 at 07:12
  • Ok, post your new `timeCalculate()` method that uses `millisUntilFinished`. – Sam Dec 12 '12 at 07:19
  • i have updated the code in the question.please take a look at it. the output is not what i expected the days text changes.Please suggest. – hemanth kumar Dec 12 '12 at 07:36
  • I agree, 20k+ days in the future is not quite right. :) `ttime` is in milliseconds, you need to divide by another 1000. The DateUtils class (android.text.format.DateUtils) has some variables to help. For example, `daysuuu = ttime / DateUtils.DAY_IN_MILLIS;`. – Sam Dec 12 '12 at 07:43
  • it shows 693 days when i change the daysuuu = ttime / DateUtils.DAY_IN_MILLIS; – hemanth kumar Dec 12 '12 at 07:55
  • Thanks for the precious help Sam. – hemanth kumar Dec 20 '12 at 04:44
2

Your problem is that you are not using Date() properly.

The parameters for java.util.Date.Date(int year, int month, int day, int hour, int minute, int second), uses 0 in the first parameter to indicate the year 1900.

The code you wrote calculates a date almost 2000 years into the future, then subtracts current time, which makes for a very long countdown ;-).

The app should work if you change the one line to

Date date = new Date(2013-1900,Integer.parseInt(datess.get(k).split("-")[1])-1,Integer.parseInt(datess.get(k).split("-")[0]),hours,mins,secs);  
gabriel
  • 1,163
  • 2
  • 9
  • 15
  • An upvote for reading the documentation on a deprecated constructor, which I clearly didn't do. – Sam Dec 19 '12 at 20:00
1

Dear use Chronometer.

int seconds;

    chronometer.setOnChronometerTickListener(new OnChronometerTickListener() 
                    {   
                        public void onChronometerTick(Chronometer chronometer) 
                        {
                            seconds = (int) ((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000);
                            String strTime = (seconds / 60) + ":" + (seconds % 60);
                            lblTime.setText(strTime);
                        }
                    });
                    chronometer.setBase(SystemClock.elapsedRealtime());
                    chronometer.start

After that try as you work. and get the day and time as you want.

Zala Janaksinh
  • 2,929
  • 5
  • 32
  • 58
0

Try this code

CountDownTimer countDown = new CountDownTimer(3000,1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFinish() {
            // TODO Auto-generated method stub

        }
    };
    countDown.start();
Ali Imran
  • 8,927
  • 3
  • 39
  • 50