JDS JDS - 4 months ago 25
Java Question

Android timer/timertask causing my app to crash?

Just testing out a simple block of code in my mainActivity's onCreate:

Timer timer2 = new Timer();
TimerTask testing = new TimerTask() {
public void run() {
Toast.makeText(mainActivity.this, "test", Toast.LENGTH_SHORT).show();

}
};
timer2.schedule(testing, 1000);


I get the "force close" error though.

What gives?

JDS JDS
Answer

Alright for anyone else who runs into this, I fixed the problem by using a Handler and Runnable to do the Toast, which seems to be needed for UI interaction:

    final Handler handler = new Handler(); 
    Timer timer2 = new Timer(); 
    TimerTask testing = new TimerTask() {
        public void run() { 
            handler.post(new Runnable() {
                public void run() {
                    Toast.makeText(mainActivity.this, "test", Toast.LENGTH_SHORT).show();
                }

            });


        }
    };
    timer2.schedule(testing, 1000);

I still don't understand why this is necessary though, perhaps someone could explain? But hey at least this code works lol.