0

I run into the problem where i have received some new data in my MainActivity and wish to pass it to a fragment inside a ViewPager. The only solution i can think of right now is to create a new ViewPager Adapter with the new data. like:

adapter = new ViewPagerAdapter(getFragmentManager(), MainActivity.this, bundle);

And in my ViewPager Adapter, i would further pass this bundle towards the fragment:

    @Override
public Fragment getItem(int arg0) {
    // TODO Auto-generated method stub

    switch(arg0){
    case 0: 
        NewBooksFrag newBookFrag = new NewBooksFrag();
        newBookFrag.setArguments(b);
        return newBookFrag;

The downside of this method is that i have to create a new adapter every time new data comes in. I am just wondering if there is a better method out there.

I have read about the

adapter.notifydatasetchange()

which calls the

getitemposition(Object object)

and then i can implement a interface which updates the object

See here

but the problem with this method is i do not know how to pass the data to the fragment i wish to update.

thanks in advance!

Community
  • 1
  • 1
Quinn Wei
  • 2,183
  • 3
  • 14
  • 12

1 Answers1

0

Let fragment take the data if you do not know how to pass it. In fragment, you create update() function that take the data from somewhere (e.g, getData() form a class). The update function is called when

adapter.notifydatasetchange();

and when you override:

getitemposition(Object object)

This data is to be updated and it should also include a field to address the fragment who should use this data (E.g, You can assign each fragment an ID).

T D Nguyen
  • 7,054
  • 4
  • 51
  • 71