Passing data among more than two fragments

Viewed 330

I successfully implemented passing data from one fragment to another fragment using interface.

MainActivity.java

MainActivity.java
public class MainActivity extends AppCompatActivity implements InputTab.SendMessage, FollowingTab.SendMessage, FollowerTab.SendMessage, ProfileTab.SendMessage, UserSearchResultTab.SendMessage {

    private SectionsPageAdapter pageAdapter;
    ViewPager viewPager;
    public static String currentUser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.container, new ProfileTab());

        fragmentTransaction.commit();

        pageAdapter = new SectionsPageAdapter(getSupportFragmentManager());

        // Sets up the ViewPager with the sections adapter

        viewPager = (ViewPager) findViewById(R.id.container);
        setupViewPager(viewPager);

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager((viewPager));

    }

    // Adds fragments to SectionsPageAdapter and gives names for the corresponding tab

    private void setupViewPager(ViewPager viewPager) {
        SectionsPageAdapter adapter = new SectionsPageAdapter(getSupportFragmentManager());
        adapter.addFragment(new InputTab(), "Search");
        adapter.addFragment(new ProfileTab(), "Profile");
        adapter.addFragment(new GithubTab(), "Github Repos");
        adapter.addFragment(new FollowerTab(), "Followers");
        adapter.addFragment(new FollowingTab(), "Followings");
        adapter.addFragment(new UserSearchResultTab(), "test");
        viewPager.setAdapter(adapter);
    }

    @Override
    public void sendDataToProfile(String message) {
        String tag = "android:switcher:" + R.id.container + ":" + 1;
        ProfileTab profile = (ProfileTab) getSupportFragmentManager().findFragmentByTag(tag);
        profile.displayReceivedData(message);
    }

    @Override
   public void sendDataToFollowers(String message) {
       String tag = "android:switcher:" + R.id.container + ":" + 3;
       FollowerTab follower = (FollowerTab) getSupportFragmentManager().findFragmentByTag(tag);
       follower.displayReceivedData(message);
   }

interface sendMessage in InputTab.java

// Interface for passing-in data to a different tab(fragment)
interface SendMessage {
    void sendDataToProfile(String message);

    //void sendDataToSearchResult(String message);
    void sendDataToResult(String message);
    //void sendDataToFollowing(String message);
}

Receiver in ProfileTab.java

// This is the part where it handles the data passed in from another fragment (tab)
protected void displayReceivedData(String message)
{
    fetchData(message);
}

This works fine, but the problem is that it does not work for more than two fragments e.g. From A -> B, C, D ...

I followed this specific tutorial : https://www.journaldev.com/14207/android-passing-data-between-fragments

So on my MainActivity.java, my sendDataToFollowers will give me an error while sendDataToProfile works fine. When I debugged it, the FollowerTab follower was null.

What would be a possible solution to make it work for more than two fragments?

2 Answers

You can try this,

Tab 0

getParent().getIntent().putExtra("key", "value"); 

Tab 1

String value = getParent().getIntent().getStringExtra("key");

Another Way :

You have to go back information to your fragment's activity. And your Activity dispatch information to its fragments :

// In fragment A
((ParentActivity)getActivity()).dispatchInformations("test");

// In ParentActivity
public void dispatchInformations(String mesg){
    fragmentB.sendMessage(mesg);
}

The best way to pass data between ViewPager's fragments is using EventBus and save the data to your Activity.

  1. Using EventBus or LocalBroadCastRecevier to send data immediately to active fragments (usually there're 3 active fragments at once).

    EventBust.getDefaut().sendData(YourDataObject);

  2. Save data in the activity, so that when the fragment is active, just pull saved data from activity in onViewCreated:

    ((YOurActivity)getActivity()).getSavedData();

Related