-4

Now i have generated a string which shows the current time. I'm wondering how to automatically refresh that string format so it could be updated. Thanks in advance

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
    String format = simpleDateFormat.format(new Date());
epiphany
  • 756
  • 1
  • 11
  • 29
  • What does “refresh that string format” mean? Change the format of the text presented to User? Or update the content with another date-time value? Both have been covered here on Stack Exchange many times already. Did you search before posting? – Basil Bourque Feb 08 '18 at 03:13

1 Answers1

0
Handler mHandler = new InnerHandler(this);
private final static int UPDATE_CURRENT_TIME = 100;
TextView tvTime;
    @Override
        protected void onStart() {
            super.onStart();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    if(isRunning){
                        mHandler.sendEmptyMessage(UPDATE_CURRENT_TIME);
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }


        private static class InnerHandler extends Handler {
            private final WeakReference<EgActivity> weakObj;

            InnerHandler(EgActivity obj) {
                this.weakObj = new EgActivity<>(obj);
            }

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                final EgActivity obj = this.weakObj.get();
                if (obj != null
                        && !obj.isFinishing()) {
                    switch (msg.what) {
                        case UPDATE_CURRENT_TIME:
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
                            String format = simpleDateFormat.format(new Date());
                            obj.tvTime.setText(format);
                            break;
                    }

                }
            }
        }
sanemars
  • 767
  • 5
  • 18