The error message is "Only the original thread..." timer schedule

Viewed 22

The error message is android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

It appears to me even though I used the corrected code for this problem, but I don't know why

    private void SparrowTimer() {
    runOnUiThread(() -> {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                //what you want to do
                SparrowAnimation();
            }
        }, 0, 6000);//wait 0 ms before doing the action and do it every 6000ms (6 sec)

        //timer.cancel();//stop the timer
    });
}

private void SparrowAnimation() {
    sparrowFlyingImage.startAnimation(animationSparrow);
}
1 Answers

The run() method of TimerTask runs on a background thread. You either need to call SparrowAnimation() from the main (UI) thread or you need to wrap the call to startAnimation() with a Runnable and ensure that it runs on the main (UI) thread like this:

private void SparrowAnimation() {
    runOnUiThread(() -> {
        sparrowFlyingImage.startAnimation(animationSparrow);
    });
}
Related