android load data asynchronously in view pager

android, android-asynctask, android-viewpager

Solution

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();
}

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();
      }
  }
  (...)

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

Problem

I need a solution for view pager implementation. Firstly I am loading huge data from database in single page,so sometimes during swipe it slows down swipe frequency(you need to multiple time swipe on page) as in background it is doing fetching task. I am not using async task for returning view. Is there any way to lazy load pages just allow user to go on other page on swipe but data is lazy loaded. My code sample is as below; ``` public Object instantiateItem(View container, int position) { View v; v = View.inflate(context,R.layout.swipearea, null); listView = (ListView)v.findViewById(R.id.MyListView); largeDataCall(); ((ViewPager)container).addView(v); return v; } ``` I am calling this in on create method. ``` pager=(ViewPager) findViewById(R.id.pagerAdapter); pager.setAdapter(new SimplePager(MyPager.this)); pager.setCurrentItem(364); ``` Is there any solution?

Original source