runOnUiThread(new Runnable() { punctuation (token) issue

Diego picture Diego · Dec 8, 2011 · Viewed 11.5k times · Source

Somehow it doesn't work, according to me it should be this:

public void Splash(){
    Timer timer= new Timer();

    timer.schedule(new TimerTask(){ 

    MexGame.this.runOnUiThread(new Runnable() {

      public void run(){
      SplashImage.setImageDrawable(aktieknop);
      } //Closes run()

      }); //Closes runOnUiThread((){})

  },SplashTime); //Closes the Timeratask((){})

} //closes Splash()

Anybody any idea where I'm missing something?

FORMAL COMMENT I know silly issue, or maybe I'm doing something impossible, but I tried all the logical possibilities. So probably missing something or I'm trying to do something that is not possible. Can you please help me out. I'm trying to use the following code, but that gives token issues:

 Timer timer= new Timer();
   timer.schedule(new TimerTask(){

     runOnUiThread(new Runnable() {

      public void run(){
      SplashImage.setImageDrawable(aktieknop);}

      });}

  },SplashTime);

If I block out the runOnUiThread it crashes since I'm trying to adapt the UI from another thread, but at least no token issue, anybody any idea?:

   Timer timer= new Timer();


  timer.schedule(new TimerTask(){

//   runOnUiThread(new Runnable() {

      public void run(){
      SplashImage.setImageDrawable(aktieknop);}

    //  });}

  },SplashTime);

Answer

THelper picture THelper · Dec 8, 2011

Both the TimerTask and the Runnable require you to implement a run method, so you'll need two run methods.

Also your code will be more easy to read if you separate the construction of the Runnable from the construction of the TimerTask.

   final Runnable setImageRunnable = new Runnable() {
        public void run() {
             splashImage.setImageDrawable(aktieknop);
        }
    };

    TimerTask task = new TimerTask(){
        public void run() {
            getActivity().runOnUiThread(setImageRunnable);
        }
    };

    Timer timer = new Timer();
    timer.schedule(task, splashTime);