public class ViewPagerTask extends TimerTask {
@Override
public void run() {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
if (viewPager.getCurrentItem() == 0){
viewPager.setCurrentItem(1);
} else if (viewPager.getCurrentItem() == 1){
viewPager.setCurrentItem(2);
} else viewPager.setCurrentItem(0);
}
});
}
}
I'm using this code to change images in a view. But the problem is I'm using it in fragment and when I change the fragment and app runs for few seconds and then suddenly pop's null pointer error. Now What I understand the reason is that it tries to change the image but doesn't find the view and create this error I have no clue what to do. Please Help :)
Error
E/AndroidRuntime: FATAL EXCEPTION: Timer-0
Process: com.example.android.indianmetro, PID: 5150
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v4.app.FragmentActivity.runOnUiThread(java.lang.Runnable)'
on a null object reference
at com.example.android.indianmetro.HomeFragment$ViewPagerTask.run(HomeFragment.java:258)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
E/AbstractTracker: Can't create handler inside thread that has not called
Looper.prepare()