-2

I have a textview, and I'm highlighting it dynamically (first 110 letters are highlighted first then after 1 second next 110 letters are highlighted and so on..). Below is my code for it.

I just created background thread as timer, but it is not stopping at all. How do I stop the timer after 3 iterations? Thanks in advance...

          int x=0;,y=110//global values
        Timer timer = new Timer();

    //Create a task which the timer will execute.  This should be an implementation of the TimerTask interface.
    //I have created an inner class below which fits the bill.
    MyTimer mt = new MyTimer();
   //We schedule the timer task to run after 1000 ms and continue to run every 1000 ms.
    timer.schedule(mt, 1000, 1000);
 class MyTimer extends TimerTask {
    public void run() {
        //This runs in a background thread.
        //We cannot call the UI from this thread, so we must call the main UI thread and pass a runnable
        if(x==330)
            Thread.currentThread().destroy();
        runOnUiThread(new Runnable() {

            public void run() {
                Spannable WordtoSpan = new SpannableString(names[0]);
                WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), x, y, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                x=x+110;
                y=y+110;
                textView.setText(WordtoSpan);
            }
        });
    }


}
joe
  • 2,468
  • 2
  • 12
  • 19
  • At the very least, read the documentation for `Timer` and `TimerTask`. search for `cancel`. – njzk2 Jul 25 '16 at 00:34
  • Possible duplicate of [How to stop the timer after certain time?](http://stackoverflow.com/questions/15894731/how-to-stop-the-timer-after-certain-time) – Sufian Jul 27 '16 at 07:42

1 Answers1

1

did you try Handler instead of timer Task?

  private static int TIME_OUT = 3000;

//--------------

new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {

                            // do your task here 
                        }
                    }, TIME_OUT);

There are some disadvantages of using Timer

It creates only single thread to execute the tasks and if a task takes too long to run, other tasks suffer. It does not handle exceptions thrown by tasks and thread just terminates, which affects other scheduled tasks and they are never run

Charuක
  • 12,953
  • 5
  • 50
  • 88
  • its not working when i use the above Handler code its saying that "unfortunately app is stopped" so please tell me whats the error in my code(which i have mentioned above) –  Jul 25 '16 at 00:33
  • whats the actual error ? can you check it on your logcat – Charuක Jul 25 '16 at 00:34
  • actually im placing texttospeech function in the task –  Jul 25 '16 at 00:52