0

I have an activity that host a fragment with Two views a mapview and viewpager that contain fragments. I don't know how to make the fragment inside viewpager communicate with the principal fragment (the fragment that have viewpager) This is the code I use :

public class ViewPagerAdapter extends FragmentPagerAdapter implements Serializable {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();
    public List<Step> steps = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

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

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

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    public void addFragment(StepsFragment fragment, Step step){
        fragment.getSteps().setText(step.getHtmlInstruction());
        mFragmentList.add(fragment);
        steps.add(step);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return null;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    }
}

I get an null pointer exception because all the fields are not initialsed ... I should be doing something wrong please help.

AndroLife
  • 908
  • 2
  • 11
  • 27

1 Answers1

1

The fragment, which contains view pager, can be accessed via getSupportFragmentManager by id/tag.

// Warning: getActivity() can be null in some cases.
Fragment fragment = getActivity().getSupportFragmentManager().findFragmentById(R.id.your_fragment);
if (fragment instanceof FragmentB)
{
   FragmentB fragmentB = (FragmentB) fragment;

}

Another approach is to do the same, but via your activity. FragmentA->Activity->FragmentB.

https://developer.android.com/training/basics/fragments/communicating.html

Dmitry
  • 149
  • 1
  • 7
  • thank you for the answer I'm trying to get some data from the fragment that contains the viewpager and send it to viewpager fragment, instead of using this way to access the fragment ... `public void addFragment(StepsFragment fragment, Step step){ fragment.getSteps().setText(step.getHtmlInstruction()); mFragmentList.add(fragment); steps.add(step); }` I should use the method you gave me ? – AndroLife May 21 '16 at 20:50
  • Ah, it is also possible. I did it before. It will be helpful: http://stackoverflow.com/questions/8785221/retrieve-a-fragment-from-a-viewpager - answered by @StreetsOfBoston. So if you are inside fragment with view pager, you can get needed fragment via view pager adapter! and send the data. – Dmitry May 21 '16 at 21:02
  • thank you so much I will try with the answer you gave me – AndroLife May 21 '16 at 21:08