0

So I'm trying to communicate between 2 fragments which are organized in a ViewPager (Swipe-tab) by using an interface I created. Like this:

The interface looks like this:

    public interface Communicator {
        public void respond(String data);
    }

On Fragment A I reference the interface calling it 'comm', the onClick of FragmentA looks like this:

    comm = (Communicator) getActivity();
    comm.respond("String being passed");

However - when I go back to my main activity in the respond override method I try to reference my fragment and I get the nullPointer exception:

    FragmentManager manager = getSupportFragmentManager();
    FragmentB fragB = (FragmentB) manager.findFragmentById(R.id.fragmentB);

Maybe I declared the ID of the fragment in the wrong way in the XML file ? I'm a beginner so I scour the net but I'm not really sure what is it that I'm looking for, any directions will also be nice

thanks in advance

shaqed
  • 342
  • 3
  • 17

1 Answers1

0

So I solved it, my problem was as @CurlyCorvus said.

To get the Id of the Fragment while using ViewPager I used this solution: Retrieve a Fragment from a ViewPager

Basically it says to Override 2 more methods to your custom adapter like this and adding another method to get the items as fragments:

   SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Fragment fragment = (Fragment) super.instantiateItem(container, position);
    registeredFragments.put(position, fragment);
    return fragment;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    registeredFragments.remove(position);
    super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
    return registeredFragments.get(position);
}

And in my method I reference my fragments like this:

 FragmentB fragB = (FragmentB) ((myAdapter) viewPager.getAdapter()).getRegisteredFragment(1);

My fragment is no longer null, and the interface is working and I can pass along data between my two fragments, thanks for your help

Community
  • 1
  • 1
shaqed
  • 342
  • 3
  • 17