1

My application has a view pager including three fragments. These are managed by a FragmentPagerAdapter.

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

        // Fragment page adapter
        mainFragmentPagerAdapter = new MainFragmentPagerAdapter(getSupportFragmentManager());

        // Set the view pagers adapter
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(mainFragmentPagerAdapter);

        // Set up the TabLayout using the view pager
        TabLayout tabLayout = (TabLayout) findViewById(R.id.fixed_tabs);
        tabLayout.setupWithViewPager(viewPager);
}

Things start to get complicated when all of these Fragments contain a RecyclerView that can be updated.

To correctly pass data to the Fragments, I'm using the newInstance method shown below:

public static InformationFragment newInstance() {
        Bundle arguments = new Bundle();
        // Put arguments here.
        InformationFragment fragment = new InformationFragment();
        fragment.setArguments(arguments);
        return fragment;
}

I then have another method inside InformationFragment to update the arguments when required:

public void updateData() {

    Bundle arguments = getArguments();
    // Put arguments
    this.adapter.updateItems(items);
}

Data that can be used to populate the RecyclerView needs to be of multiple types (some android, some custom). Therefore, I have ArrayList<Object> items; containing all my objects.

My question is, what is the best way to store this ArrayList in a bundle so it can be used by a fragment?

I am able to do the following, but it feels dirty:

public void updateData(ArrayList<Object> items) {
        getArguments().putSerializable("items", items);
        this.adapter.updateItems(items);
    }

and then retrieve by:

if (arguments.containsKey("items")) {
            ArrayList<Object> items = (ArrayList<Object>)arguments.getSerializable("items");
}

Or is there a better approach?

ritch
  • 1,760
  • 14
  • 37
  • 65

1 Answers1

0

I would recommend NOT keeping a List<Object> and instead put multiple lists into your bundle. Also putting your objects into the bundle as a serializable really isn't that bad, but if you want to do it the more androidy way you can implement the Parcelable interface for each object that is being stored inside that bundle.

Charles Durham
  • 2,445
  • 16
  • 17