In my application there are several fragments that I switch in the side menu, and in one of the fragments I have a ViewPager in which Timer automatically scrolls through the pages (every 5 seconds), but there is a problem when I change the fragment:

MainActivity.java

fragmentmanager = getSupportFragmentManager(); fragmentmanager.beginTransaction().replace(R.id.frame, fragment).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN).commit(); 

After a few seconds, the application crashes, and the logs say that Timer is to blame for everything:

Log

 FATAL EXCEPTION: Timer-1 Process: ru.zoomania.app, PID: 20391 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.runOnUiThread(java.lang.Runnable)' on a null object reference at ru.zoomania.app.fragments.MainFragment$100000002$0$debug.run(MainFragment.java:129) at ru.zoomania.app.fragments.MainFragment$100000002.run(MainFragment.java) at java.util.Timer$TimerImpl.run(Timer.java:284) 

Here is the timer code

Fragment.java

 TimerTask timertask; Timer timer = new Timer(); timertask = new TimerTask() { @Override public void run() { getActivity().runOnUiThread(new Runnable(){ @Override public void run() { int i = vpPager.getCurrentItem(); if(vpPager.getAdapter().getCount()-1!=i){ vpPager.setCurrentItem(i+1); } else { vpPager.setCurrentItem(0); } } }); } }; timer.scheduleAtFixedRate(timertask, 5000,5000); 

My task is how to turn off the timer in the fragment from the activation

  • In the onPause() fragment, stop in onResume . I think it would be logical - if the fragment is suspended, then flipping through the pages to nothing. - woesss
  • I did all this, and onDestroy , and onDestroyView , onPause , onStop , nothing helps. The problem is that when I try to stop him in onStop he returns to me that the timer is null - Alex Kulich
  • Probably you do not write an instance of it in the class field, but create a local variable of the same name in the method, start and exit the method, the reference to the timer is lost. Try after creating a timer to add this.timer = timer; in the same method this.timer = timer; (on the left is the name of the field, on the right of the local variable - substitute your own if you are different). Or show the entire fragment. Not relevant to the question can be removed, leave only the code where you use the timer (including your idle attempt) - woesss

1 answer 1

The solution was very simple, you just had to cancel TimerTask in onPause() or a similar life cycle when onPause() fragment:

 @Override public void onPause() { super.onPause(); if(timertask != null) { timertask.cancel(); timertask = null; } else { Log.i("LogYourApp","onPause() timertask is null); } }