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
onPause()fragment, stop inonResume. I think it would be logical - if the fragment is suspended, then flipping through the pages to nothing. - woesssonDestroy, andonDestroyView,onPause,onStop, nothing helps. The problem is that when I try to stop him inonStophe returns to me that the timer isnull- Alex Kulichthis.timer = timer;in the same methodthis.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