user3908859
user3908859

Reputation: 13

fatal exception timer-0 error

I'm new to programming so I have no idea most of errors, what they mean?. It would really help if someone could tell me how to solve this error.

What im trying to do with this set of codes is have a picture fade in and display for a few seconds, and fade out after a few seconds.

the codes are in onCreate()

final ImageView wavem = (ImageView)findViewById(R.id.wavem);
        final Animation animationFadeIn = AnimationUtils.loadAnimation(this, R.drawable.fadein);
        final Animation animationFadeOut = AnimationUtils.loadAnimation(this, R.drawable.fadeout);
        final int time = 8000;
        final int readtime = 4000;

    new java.util.Timer().schedule( 
            new java.util.TimerTask() {
                    @Override
                    public void run() {
                    wavem.startAnimation(animationFadeIn);

                        new java.util.Timer().schedule( 
                        new java.util.TimerTask() {
                        @Override
                        public void run() {
                        wavem.startAnimation(animationFadeOut);
                                          }}, readtime);
                    }
            }, time 
            );

The error log I get is:

08-05 04:18:36.428: E/AndroidRuntime(972): FATAL EXCEPTION: Timer-0
08-05 04:18:36.428: E/AndroidRuntime(972): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
08-05 04:18:36.428: E/AndroidRuntime(972):  at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4607)
08-05 04:18:36.428: E/AndroidRuntime(972):  at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:867)
08-05 04:18:36.428: E/AndroidRuntime(972):  at android.view.ViewGroup.invalidateChild(ViewGroup.java:4066)
08-05 04:18:36.428: E/AndroidRuntime(972):  at android.view.View.invalidate(View.java:10250)
08-05 04:18:36.428: E/AndroidRuntime(972):  at android.view.View.startAnimation(View.java:15449)
08-05 04:18:36.428: E/AndroidRuntime(972):  at java.util.Timer$TimerImpl.run(Timer.java:284)

I really appreciate any help.

Upvotes: 1

Views: 2247

Answers (1)

Rajen Raiyarela
Rajen Raiyarela

Reputation: 5636

error is coming because you have create view "wavem" using UI thread and you are changing it in thread created by TimerTask.

So inside timetask instead of just doing

wavem.startAnimation(animationFadeIn);

do as on both places

runOnUiThread(new Runnable(){
public void run() {
  wavem.startAnimation(animationFadeIn);
}
});

Upvotes: 1

Related Questions