Here is my view pager adapter to load fragments. Inside the getItem() method, I am trying to insert the values dynamically using the index passed to that function. I have all the data inside productData. But it always fetches the value of
productData.get(0).get("name")
into all the fragments. The index value is correctly being passed into fragments. I verified it. And also the data inside the productData is also correct. Where is the issue here?
public class ProductViewPagerAdapter extends FragmentPagerAdapter {
public ProductViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int i) {
Fragment fragment = new ProductViewFragment();
Bundle args = new Bundle();
args.putInt("number", i + 1);
args.putString("name", productData.get(i).get("name"));
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return 10;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return "test1";
case 1: return "2";
case 2: return "3";
case 3: return "4";
}
return null;
}
}
The problem is that you only have a single
HashMap. Even though you keep changing the data inside theHashMap, the listproductItemsjust contains 10 references to the singleHashMap. So in the end, it will contain 10 copies of the final set of data.What you want to do is create a new
HashMapfor each loop iteration. Here’s the modified code: