我在我的主课程中运行以下代码,只是为了让计数器倒数到圣诞节前的天,小时,分钟和秒。从我所看到的,我认为我的代码是正确的(虽然,因为它抛出异常,它可能不是)。谁能看到错误是什么?
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);
堆栈跟踪如下......
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)
第44行是mTextField.setText(“Days:”+ diffDays +“Hours:”+ diffHours +“Minutes:”+ diffMinutes +“Seconds:”+ diffSeconds);
答案 0 :(得分:2)
尝试使用处理程序而不是计时器,从日志中看,问题是您无法从timerTask更改UI。
http://developer.android.com/reference/android/os/Handler.html
这里有一些很好的例子:
How to run a Runnable thread in Android?
使用postDelayed在操作之间提供延迟。
你的逻辑有缺陷,看起来应该更像这样:
diff = diff /1000;
final long diffSeconds = diff % 60;
diff = diff / 60;
final long diffMinutes = diff % 60;
...
我没有对此进行测试,但应该可以使用。
答案 1 :(得分:0)
您无法与线程中的视图进行交互。 Timer基本上是一个Thread。你必须在这里使用一个带有计时器的处理程序。