user2520217 user2520217 - 1 month ago 7
Android Question

Android FragmentStatePagerAdapter Preload Fragment

3 fragments will displayed on ViewPager with FragmentStatePagerAdapter.

I named those fragments and 3 fragments have customed layout


1.StepOneFragmet

2.StepTwoFragmet

3.StepThreeFragmet


I need to fetch the data from Server and binding those data into different fragment separately. How can i create and initialized 3 fragments when i loaded the viewpager?

If i access StepThreeFragment, it will return NullpointerException. It means that the system haven't create and initialize the Fragment.

There are my codes:

Activity:

mPager = (ViewPager) findViewById(R.id.pager);
mFragments = new ArrayList<>();
mFragments.add(new StepOneFragment());
mFragments.add(new StepTwoFragment());
mFragments.add(new StepThreeFragment());

mPagerAdapter = new StepPagerAdapter(getSupportFragmentManager(),mFragments);
mPager.setAdapter(mPagerAdapter);

StepThreeFragment f = (StepThreeFragment)((StepPagerAdapter) mPager.getAdapter()).getmFragments().get(2);
f.textView_profile.setText("1111");//--->NullPointerException


StepPagerAdapter:Code

public ArrayList<Fragment> getmFragments(){
return mFragments;
}

@Override
public int getCount() {
return 3;
}

@Override
public Fragment getItem(int position) {
return mFragments.get(position);
}


StepThreeFragment: (For example -> setText of TextView)

Code

Answer

Activity:

//assign MyObject some valu form your web services

mPagerAdapter = new StepPagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.addFragments(MyObject obj);

StepOneFragment.java

    public static final StepOneFragment newInstance( MyObject obj ){

    StepOneFragment f = new StepOneFragment();

    // Get arguments passed in, if any
    Bundle args = f.getArguments();
    if (args == null) {
        args = new Bundle();
    }

    // Add parameters to the argument bundle
    args.putParcelable("obj", obj );          // clone or referenced?

    MyObject implements parcelable
    f.setArguments(args);

    return f;

    }

     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MyObject object = getArguments().getParcelable("obj");

     }

Fragmentstatepageradapter:

public fraf extends FragmentStatePagerAdapter{

    List<Fragment> fragments = new ArrayList();

    public fraf(FragmentManager fragmentManager) {
         super(fragmentManager);
    }

    public void addFragments(Myobject obj){

        fragments.add(StepOneFragment.newInstance(obj));
        fragments.add(StepTwoFragment.newInstance(obj));
        fragments.add(StepThreeFragment.newInstance(obj));
        notifydatasetchanged();

     }

     @Override
     public int getCount() {
        return fragments.size();
     }

     @Override
     public Fragment getItem(int position) {
        return mFragments.get(position);
     }
}