How to make an ImageSwitcher switch the image every 5 secs?

1.8k views Asked by At

Im trying to get an ImageSwitcher to change an image every 5 secs..

I tried using a Timer:

Timer t = new Timer();
          //Set the schedule function and rate
          t.scheduleAtFixedRate(new TimerTask() {

              public void run() {
                  //Called each time when 1000 milliseconds (1 second) (the period parameter)
                  currentIndex++;
                // If index reaches maximum reset it
                 if(currentIndex==messageCount)
                     currentIndex=0;
                 imageSwitcher.setImageResource(imageIds[currentIndex]);
              }

          },0,5000);

But I get this error:

LOGCAT:

12-14 15:07:29.963: E/AndroidRuntime(25592): FATAL EXCEPTION: Timer-0
12-14 15:07:29.963: E/AndroidRuntime(25592): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
2

There are 2 answers

0
whizzzkey On BEST ANSWER
Timer t = new Timer();
      //Set the schedule function and rate
      t.scheduleAtFixedRate(new TimerTask() {

          public void run() {
              //Called each time when 1000 milliseconds (1 second) (the period parameter)
              currentIndex++;
            // If index reaches maximum reset it
             if(currentIndex==messageCount)
                 currentIndex=0;
             runOnUiThread(new Runnable() {

                public void run() {
                   imageSwitcher.setImageResource(imageIds[currentIndex]);

                }
          });
          }

      },0,5000);
0
Raghunandan On
Only the original thread that created a view hierarchy can touch its views.

Timer task runs on a different thread. Ui should be updated on the ui thread.

Use runOnUiThread.

runOnUiThread(new Runnable() {

        public void run() {
         imageSwitcher.setImageResource(imageIds[currentIndex]);

        }
    });

You can also use Handler instead of timer.

Edit:

Check this setBackgroundResource doesn't set the image if it helps