I have a ViewPager with a TabLayout. I have created ViewPagerAdapter by extending FragmentStatePagerAdapter. When i swipe ViewPager i got the following error
FATAL EXCEPTION: main
Process: com.anubavam.creatrix, PID: 21388
java.lang.IllegalStateException: Fragment already added: AttendanceViewFragment
Here is ViewPagerAdapter Class code
private class ViewPagerAdapter extends FragmentStatePagerAdapter {
private List<AttendanceViewFragment> mFragments = new ArrayList<>();
private ArrayList<String> buttons = new ArrayList<>();
ViewPagerAdapter(FragmentManager fm, ArrayList<String> actionButtons) {
super(fm);
this.buttons = actionButtons;
}
void addFragment(AttendanceViewFragment frag) {
mFragments.add(frag);
}
@Override
public Fragment getItem(int position) {
return new AttendanceViewFragment();
}
@Override
public int getCount() {
return mFragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return buttons.get(position);
}
}
This is the way i added Fragments into ViewPager Adapter:
adapter = new ViewPagerAdapter(getSupportFragmentManager(), titles);
for (int i = 0; i < titles.size(); i++) {
//order of the fragment
if (i == 0) {
adapter.addFragment(AttendanceViewFragment.newInstance(studentList.toString(), "T"));
} else if (i == 1) {
adapter.addFragment(AttendanceViewFragment.newInstance(present.toString(), "P"));
} else if (i == 2) {
adapter.addFragment(AttendanceViewFragment.newInstance(absent.toString(), "A"));
} else if (i == 3) {
adapter.addFragment(AttendanceViewFragment.newInstance(late.toString(), "L"));
}
}
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
I tried with FragmentPagerAdapter instead of FragmentStatePagerAdapter. But no use. Suggest me any other approach to solve this issue.