Working with fragment with its holder Activity…. often used concept | Techbirds

hello Again Folks,

I was working with fragments that are binding json data from API call but as fragments on swiped in calls my Async task that does the binding stated. but when switched to back and forth with fragments makes the crashes. for the same i found the following discussed solution to make it work. i write whenever i feel it may help others in similar tasks.

Concept:

I would suggest to work with Fragments (and not directly with views).

You need an Interface on your fragments to tell them when they are shown:

public interface IShowedFragment { public void onShowedFragment(); }

public interface IShowedFragment {

    public void onShowedFragment();

}

Make all your fragments implement that interface, and in that method call your loaders/asyncTasks/background tasks.

Then put an onPageChangeListener on your ViewPager, and when you detect the user changed the page, call the interface method on your fragment. You have some choices with this listener, with one of the methods you can wait for the viewPager to stop to slide to trigger your interface call.

To be able to get the right fragment to make this call, take the fragment from yourFragmentApadter.instantiateItem(ViewGroup, int) which will return the fragment for that position if it is already loaded.

mPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { Fragment fragment = (Fragment) mAdapter.instantiateItem(mPager, position); if(fragment instanceof IShowedFragment){ ((IShowedFragment) fragment).onShowedFragment(); } (…)

mPager.setOnPageChangeListener(new OnPageChangeListener() {

  @Override

  public void onPageSelected(int position) {

      Fragment fragment = (Fragment) mAdapter.instantiateItem(mPager, position);

      if(fragment instanceof IShowedFragment){

      ((IShowedFragment) fragment).onShowedFragment();

}

(…)

}

Like that you can prepare your fragments with empty views and when you slide on one, you start to load the data.

Tapan Saini

Android Trainee

498 total views, 1 views today

Share this Onfacebook-2241100twitter-9772429linkedin-3689937google-8810879