I recently refactored an old project and found that a particular portion no longer wants to run properly no matter what I do. Essentially, I have an Activity with a TextView. This view is updated at timed intervals from a thread invoked within the same class. The pause is accomplished with a Thread.sleep and a Handler is used to trigger the update of the UI. The thing is, now I either get a CalledFromWrongThreadException saying that I cannot manipulate the View from another thread, a long pause followed by all the text hitting the View at once, or it seemingly fires off immediately and doesn't sleep at all. I had previously done it like so (relevant parts included):
public class Updated extends Activity implements Runnable {
private TextView textView;
private String text;
private Handler handle = new Handler(){
@Override
public void handleMessage(Message msg){
textView.append(text);
}
};
//onCreate and other such things...{
new Thread(this).start();
}
public void run(){
//A healthy chunk of logic/conditionals
text = "Blah blah";
handle.sendEmtpyMessage(0);
try {
Thread.sleep(1500l);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
That's the gist of what I was using previously, which worked fine. However, I really didn't like the practice of setting a class variable and then having the Handler grab it later. I modified it to pass a Message with the .obj field set to a String, which would then be peeled out and appended to the TextView. This would blow up with the aforementioned exception. I tried leaving the Handler declaration in place, but moving the logic within to another method where the Handler would .post(Runnable(){}); with the same guts, but that would just stall and append it after a significant wait. I'm not terribly savvy with the inner workings of Handlers and Threads within Java/Android, so any pointers would be quite welcome.