I'm running the following code in my main class, just to have a counter that counts down the days, hours, minutes and seconds until Christmas. From what I can see, I think my code is correct (although, as it's throwing an Exception, it's probably not). Can anyone see what the error is?
final TextView mTextField = new TextView(this);
Calendar xmas = Calendar.getInstance();
Calendar now = Calendar.getInstance();
xmas.set(2011, 12, 25);
long milliseconds1 = now.getTimeInMillis();
long milliseconds2 = xmas.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
final long diffSeconds = diff / 1000;
final long diffMinutes = diff / (60 * 1000);
final long diffHours = diff / (60 * 60 * 1000);
final long diffDays = diff / (24 * 60 * 60 * 1000);
int delay = 1000; // delay for 1 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
mTextField.setText("Days : " + diffDays + " Hours : " + diffHours + " Minutes : " + diffMinutes + " Seconds : " +diffSeconds);
}
}, delay, period);
setContentView(mTextField);
The stack trace is as follows...
10-29 17:27:19.258: ERROR/AndroidRuntime(471): FATAL EXCEPTION: Timer-0
10-29 17:27:19.258: ERROR/AndroidRuntime(471): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at android.view.ViewRoot.checkThread(ViewRoot.java:2932)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at android.view.ViewRoot.requestLayout(ViewRoot.java:629)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at android.view.View.requestLayout(View.java:8267)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at android.view.View.requestLayout(View.java:8267)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at android.view.View.requestLayout(View.java:8267)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at android.view.View.requestLayout(View.java:8267)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at android.widget.TextView.checkForRelayout(TextView.java:5514)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at android.widget.TextView.setText(TextView.java:2724)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at android.widget.TextView.setText(TextView.java:2592)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at android.widget.TextView.setText(TextView.java:2567)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at com.android.sleeps.SleepstosantaActivity$1.run(SleepstosantaActivity.java:44)
10-29 17:27:19.258: ERROR/AndroidRuntime(471): at java.util.Timer$TimerImpl.run(Timer.java:284)
Line 44 is mTextField.setText("Days : " + diffDays + " Hours : " + diffHours + " Minutes : " + diffMinutes + " Seconds : " +diffSeconds);