Android: FragmentPagerAdapter: getItem method called twice on First time

Sridhar picture Sridhar · Mar 5, 2013 · Viewed 16.7k times · Source

In My application, I have used the ViewPager. Like,

(say main.xml)

<android.support.v4.view.ViewPager
     android:id="@+id/viewPager"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent"
     android:layout_above="@+id/register_header" />

And Create ViewPager object and ViewPagerAdapter(which extends FragmentPagerAdapter) object in FragmentActivity.

_mViewPager = (ViewPager) findViewById(R.id.viewPager);

_adapter = new ViewPagerAdapter(getApplicationContext(),
         getSupportFragmentManager());

_mViewPager.setAdapter(_adapter);

And the Adapter class is like,

public class ViewPagerAdapter extends FragmentPagerAdapter {
    private Context _context;
    private FragmentManager manager;
    private Fragment f;
    private String classname="ViewPagerAdapter";
    public ViewPagerAdapter(Context context, FragmentManager fm) {
        super(fm);  
        _context=context;
        manager=fm;
        }
    @Override
    public Fragment getItem(int position) {
        Log.i(classname,"getItem called"+position);
        f = new Fragment();
        f=MyFragment.newInstance();
        Bundle args = new Bundle();
        args.putInt("position", position);
        f.setArguments(args);
        return f;
    }

    @Override
    public int getCount() {
        return User.getPageCount();
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }
}

And in MyFragment Class,

In onResume , I have to store the wigets object to the common static variable.

public void onResume() {
        super.onResume();
        pageIndex = getArguments().getInt("position");      
        User.useTextview1=textview1;
        User.useTextview2= textview2;
        User.current_pageIndex=pageIndex;



    }

I have to update the textviews got from the User class in the FragmentActivity. My Problem is getItem() method is called twice on First time In Fact , the view displayed in the emulator is 0th index, but got 1st Index value in the FragmentActivity. If I stopped the calling of getItem() method on second time, I can able to get the 0th index TextView reference in the FragmentActivity.

Please provide me the best way to do this.

Thanks

Answer

Niko picture Niko · Mar 5, 2013

The FragmentPagerAdapter instantiates 2 Fragments on start, for index 0 and for index 1. If you want to get data from the Fragment which is on the screen, you can use setOnPageChangeListener for the Pager to get current position. Then have SparseArray with WeakReference to your fragments. Update that array in the getItem call. When onPageSelected gets called use that position to get reference to right Fragment and update User data.

Initialization of array:

private SparseArray<WeakReference<MyFragment>> mFragments = new SparseArray<WeakReference<MyFragment>>(3);