Skip to content Skip to sidebar Skip to footer

How To Update Time Every Second In Java Emulator?

I have been working on a code for an app but I cannot get the time to update in the emulator when I run the code. The code works in the compiler but not the emulator. Any helpful s

Solution 1:

Keeping things very simple, I'd remove all Executors stuff and do something like:

TextView daysBox = (TextView) findViewById(R.id.s1Days);

// We create a runnable that will re-call itself each second to update time
Runnable printDaysToXmas=new Runnable() {

   @Override
   publicvoid run() {
      Calendar today = Calendar.getInstance();
      long diff = (thatDay.getTimeInMillis() - today.getTimeInMillis()) / 1000;
      long days = diff / (60 * 60 * 24);
      long hours = diff / (60 * 60) % 24;
      long minutes = diff / 60 % 60;
      long seconds = diff % 60;

      daysBox.setText(" + "" + days + "" + hours + "" + minutes + "" + seconds + "");

      // we call this runnable again in 1000ms (1 sec)
      daysBox.postDelayed(printDaysToXmas, 1000); // all views have a Handler you can use ;P
   }
};

... and to start the process just do

printDaysToXmas.run();

... and to stop it, you can do

daysBox.removeCallbacks(printDaysToXmas);

Solution 2:

Also some little add to rupps answer. You can use

DateUtils.getRelativeTimeSpanString(long time, long now, long minResolution);

to simplify math and give more user readable string for user.

Post a Comment for "How To Update Time Every Second In Java Emulator?"