1

I'd like to accomplish something which I would think to be simple, but is turning out to be a hassle.

I have a loading screen with a picture, and I'd like for it to fade in and out as the application is loading. I decided to accomplish this by changing it's opacity frequently relative to the sine value of a counter. My code is as follows:

ImageView   loadingRaven;   //loading raven at the start of the app
Timer       timer;          //timer that we're gonna have to use
int         elapsed = 0;    //elapsed time so far

/*
 * the following is in the onCreate() method after the ContentView has been set
 */

loadingRaven = (ImageView)findViewById(R.id.imageView1);


//fade the raven in and out
TimerTask task = new TimerTask()
{
    public void run()
    {
        elapsed++;

        //this line causes the app to fail
        loadingRaven.setAlpha((float)(Math.sin(elapsed)+1)/2);
    }
};
timer = new Timer();
timer.scheduleAtFixedRate(task, 0, 50);

What is the problem that's causing my program to fail? Am I correctly using Timer and TimerTask? Or is there perhaps a better way to update the opacity of the image frequently so it eases in and out smoothly?

Thanks

Abe Fehr
  • 729
  • 9
  • 23

1 Answers1

2

TimerTask runs on a different thread. So update ui on the main ui thread. Use runonuithread

      TimerTask task = new TimerTask()
      {
        public void run()
         {
          elapsed++;
              runOnUiThread(new Runnable() //run on ui thread
                 {
                  public void run() 
                  { 


                     loadingRaven.setAlpha((float)(Math.sin(elapsed)+1)/2)
                 }
                 });

     }
  };

TimerTask runs on a different thread. You can use Handler and postDelayed as suggested by pskink

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • why to make own life harder and complicated? why don't you use a Handler and postDelayed? – pskink May 09 '13 at 16:00
  • @pskink you can also use a handler. since OP was using a timertask i posted the solution. i also said timertask runs on a different thread. yup better to use a handler – Raghunandan May 09 '13 at 16:00
  • Sorry @Raghunandan, StackOverflow was making me wait a few minutes before I could accept the answer – Abe Fehr May 09 '13 at 16:02
  • @pskink, I'm not familiar with those, I'm relatively new to Android Development. I'll look 'em up! – Abe Fehr May 09 '13 at 16:03
  • read one of many posts about Handlers, for example this http://arjun30.blogspot.com/2012/05/handler-in-android.html?m=1 – pskink May 09 '13 at 16:54
  • http://stackoverflow.com/questions/6207362/how-to-run-an-async-task-for-every-x-mins-in-android. also check the answer in the link – Raghunandan May 09 '13 at 16:58