0

I have a TimerTask running inside one of the fragment of my app; when I try to switch dinamically to another fragment using the "fragmentManager.beginTransaction().replace" method my app crashes. I'm sure that my issue is linked with the Timer bucause if I comment it everything works perfectly. Here is the Timer code inside my fragment:

     public void startTimer(ProgressBar b){
     final ProgressBar bar = b;
      t = new Timer();   
      task = new TimerTask() {

        @Override
       public void run() {
        getActivity().runOnUiThread(new Runnable() {

          @Override
         public void run() {
              bar.setMax(3600);
          bar.setProgress(mytime);
          //TextView tv1 = (TextView) getView().findViewById(R.id.textView2);
          //tv1.setText("TIME LEFT:" +time);
          if (mytime <= 3600)
           mytime += 1;
          else {
           //tv1.setText("GAME OVER");           
          }
         }
        });
       }
      };
      t.scheduleAtFixedRate(task, 0, 1000);
     }

Maybe I can't change fragment while I'm running the TimerTask on the UiThread? Thanks for any answer.

Moltehh
  • 247
  • 1
  • 3
  • 12
  • Sooooo....what's the error? Oh let me guess ... NPE at bar.setMax()? What about stopping the timer when changing fragments? – ElDuderino Apr 23 '14 at 10:26

3 Answers3

1

Use Handler Thread in place of Timer task.

Handler thread is a separate thread created from UI thread. so it can talk with the UI thread and you can change Activity/Fragment.

Make sure you remove all callbacks to handler before you change fragment

like this:

    final Handler handler=new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {
            if(condition)
            {
                handler.removeCallbacks(this);
            }
            else
            {
                handler.postDelayed(this,3600);
            }
        }
    }, 3600);
Viral Thakker
  • 547
  • 2
  • 10
0

If the timer is scheduled twice for the same task, it might crash. And also for updating the UI from the timer task you might have to use the handler

Reference: Android timer updating a textview (UI)

Community
  • 1
  • 1
vikki_logs
  • 1,521
  • 2
  • 10
  • 21
0

From documentation: replace()

Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.

Your fragment is destroyed after calling replace(), I think that you should use method addToBackStack() or use hide() method or stop a timer in onDestroy() method.

Volodymyr
  • 1,037
  • 1
  • 11
  • 27