I am new android and I would appreciate some help. I have this code:
dateatm = (TextView) findViewById(R.id.date);
timeatm = (TextView) findViewById(R.id.tvTime);
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MMM/dd");
SimpleDateFormat värk = new SimpleDateFormat("HH:mm:ss");
String dateNow = formatter.format(currentDate.getTime());
String timeNow = värk.format(currentDate.getTime());
dateatm.setText(dateNow);
timeatm.setText(timeNow);
As you can see, I am getting date and time out of it. What I want tho is that there would be 1 second loop, so after every 1 second, it will update date and time again and again to the newer one to get basically clock. I am pretty newcomer so all help is appreciated how to get this done. If you would bring exact examples I would appreciate as it makes it more easier to understand, not just “Oh, use that and that and that. Thank you!”.
Thanks for your help and time,
Elven 🙂
Error for answer 1:
08-10 18:55:41.335: ERROR/AndroidRuntime(886): FATAL EXCEPTION: Timer-0
08-10 18:55:41.335: ERROR/AndroidRuntime(886): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at android.view.ViewRoot.invalidateChild(ViewRoot.java:642)
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:668)
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at android.view.ViewGroup.invalidateChild(ViewGroup.java:2511)
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at android.view.View.invalidate(View.java:5279)
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at android.widget.TextView.checkForRelayout(TextView.java:5507)
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at android.widget.TextView.setText(TextView.java:2724)
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at android.widget.TextView.setText(TextView.java:2592)
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at android.widget.TextView.setText(TextView.java:2567)
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at viimane.voimalus.MainStuff$1.run(MainStuff.java:55)
08-10 18:55:41.335: ERROR/AndroidRuntime(886): at java.util.Timer$TimerImpl.run(Timer.java:284)
I just solved this issue in my project (executing code at specific interval) 🙂
Edited to reflect updated answer:
// Initialization code in onCreate or similar: