In my app there's an Activity with three tabs, each of them contains a ListFragment. The ListFragment must show different contents, but when I pass it through the bundle it gets overwritten and I get three fragments with the same content (the latest one) Here's the code:
In the onCreate method of the Activity:
{...
Fragment fragment;
Bundle bundle= new Bundle();
for(int i = 0; i<CATEGORIES.size(); i++) {
fragment = new MyListFragment();
bundle.putSerializable("Data", data.get(i));
fragment.setArguments(bundle);
screens.put(CATEGORIES.get(i),fragment);
}
setUpViewPagerAndTabs();
...
... }
protected void setUpViewPagerAndTabs(){
mViewPager = (ViewPager) findViewById(R.id.viewpager);
mViewPager.setOffscreenPageLimit(screens.size()+1);
mAdapter = new PageAdapter(screens, getSupportFragmentManager());
mViewPager.setAdapter(mAdapter);
tabs = (TabLayout) findViewById(R.id.tabs);
tabs.setTabGravity(TabLayout.GRAVITY_FILL);
tabs.setTabMode(TabLayout.MODE_FIXED);
tabs.setupWithViewPager(mViewPager);
}
In the Fragment class this line produces the overwriting of the corresponding data:
ArrayList<String> names = (ArrayList<String>)
b.getSerializable(Activity.DATA);
even if I try to pass the value of the counter (i) to the fragment, in order to pick the right element of data in the fragment, it gets overwritten. How can I resolve this? Thank you in advance
Not sure if it is the case. However you are passing the reference to the same bundle (out of the scope) to all the three fragments. It might depend on when the serialization / deserialization takes effect, but if it happen after the loop you have three fragment pointing to the same content of the bundle (the last one).
Try to move the bundle creation inside the loop:
for(int i = 0; i<CATEGORIES.size(); i++) {
Bundle bundle= new Bundle();
fragment = new MyListFragment();
bundle.putSerializable("Data", data.get(i));
fragment.setArguments(bundle);
screens.put(CATEGORIES.get(i),fragment);
}