Reputation: 2419
I am trying to schedule a task to update a TextView once a second. As long as I have the line, with the comment after it, commented out, everything works fine. Logcat shows someting like:
Task
IN
OUT
Task
IN
OUT
...
But if I uncomment the statusLabel.setText(), this is what I see:
Task
IN
OUT
TASK
IN
Those five rows are all I get. For some reason it seems to stop, when it tries to set the text again the second time.
My Code:
public class MyActivity extends Activity {
TextView statusLabel;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.control);
statusLabel = (TextView) findViewById(R.id.statusLabel);
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(
new Runnable() {
public void run() {
Log.d("Datalogger","Task");
updateStatus();
}
}, 0, 1, TimeUnit.SECONDS);
}
private void updateStatus() {
Log.d("Datalogger","IN");
statusLabel.setText("X"); // !! If I comment out this line,
Log.d("Datalogger","OUT"); // everything works
}
}
Upvotes: 0
Views: 475
Reputation: 2508
The problem is that you are attempting to update UI from a thread other than the UI(main) thread. In the runnable use runOnUiThread(Runnable action) with a new runnable to call updateStatus().
Upvotes: 2
Reputation: 63955
You can't update the UI from a background thread. There should even be an error about that in your Log. Use Activity#runOnUiThread(Runnable)
Upvotes: 1