This is what I am trying to do:
I have ViewPager in my Activity which hosts 6 Fragment. I disabled paging by swiping with finger, so whenever I want to swipe I use related button and :
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
In each fragment that is swiped (after swipe is finished) I want to send a GET request to my server and fetch some data and show it in that fragment. for doing that:
First Approach : I used this code in my fragments which runs as soon as fragment become visible:
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser)
{
sendGetRequest();
}
}
But , here was a problem : that setUserVisibleHint executes exactly whene the fragment visible , and because of that the animation of swiping came with some lag(it wasn't smooth enough).
So I used Second Approach : I added an OnPageChangeListener() to ViewPager in hosted activity like this :
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
int CurrentPossition = 0;
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
@Override
public void onPageSelected(int position) {
CurrentPossition = position;
}
@Override
public void onPageScrollStateChanged(int state) {
if(state == ViewPager.SCROLL_STATE_IDLE && CurrentPossition != 0){
Toast.makeText(getBaseContext(),"finished" , Toast.LENGTH_SHORT).show();
try{
new fragment_two().sendGetRequest();;
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
It works great, and toast shows as soon as swipe finished, but unlike fragment which visible completely , when sendGetRequest() runs i get NullPointerException.
here is StackTrace :
04-08 20:15:37.840 12848-12848/com.example.mohamad.travelagency W/System.err: java.lang.NullPointerException
04-08 20:15:37.850 12848-12848/com.example.mohamad.travelagency W/System.err: at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
04-08 20:15:37.850 12848-12848/com.example.mohamad.travelagency W/System.err: at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:103)
04-08 20:15:37.850 12848-12848/com.example.mohamad.travelagency W/System.err: at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:143)
any idea would be great.
Thanks in advance !!!