0

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.

4
  • 1
    post AttendanceViewFragment.newInstance method Commented May 15, 2017 at 7:46
  • public static AttendanceViewFragment newInstance(String s, String t){ AttendanceViewFragment fragTt = new AttendanceViewFragment(); Bundle bundTottal = new Bundle(); bundTottal.putString("data", s); bundTottal.putString("flag", t); fragTt.setArguments(bundTottal); return fragTt; } Commented May 15, 2017 at 8:38
  • add this code :if (titles.size()>1){ viewPager.setOffscreenPageLimit(titles.size()-1); } after viewPager.setAdapter(adapter); Commented May 15, 2017 at 9:09
  • and change private List<AttendanceViewFragment> mFragments = new ArrayList<>(); to private List<Fragment> mFragments = new ArrayList<>(); Commented May 15, 2017 at 9:11

2 Answers 2

2

In other hand you can use viewpager2 with this code:

myPagerAdapter.kt

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter


class PagerAdapterAccounting internal constructor(fm: FragmentActivity) : FragmentStateAdapter(fm) {

    override fun getItemCount(): Int {
        return mFragmentList.size
    }

    override fun createFragment(position: Int): Fragment {
        return mFragmentList[position]
    }

    private val mFragmentList = ArrayList<Fragment>()
    private val mFragmentTitleList = ArrayList<String>()


    fun addFragment(fragment: Fragment, title: String) {
        mFragmentList.add(fragment)
        mFragmentTitleList.add(title)
    }

    fun getTabTitle(position: Int): String {
        return mFragmentTitleList[position]
    }
}

Ui:

 <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/colorPrimaryDark"
        app:tabIndicatorHeight="2dp"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/colorPrimary" />

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

and the usage:

val fragmentAdapter = PagerAdapterAccounting(this) //must be a fragmentActivity

fragmentAdapter.addFragment(SampleFragment.newInstance(), "theSampleTitle1")
fragmentAdapter.addFragment(SampleFragment2.newInstance(), "theSampleTitle2")

viewPager.adapter = fragmentAdapter

TabLayoutMediator(tabLayout, viewPager,
                TabLayoutMediator.TabConfigurationStrategy { tab, position -> tab.text =  fragmentAdapter.getTabTitle(position) }).attach()

dont forget to add appcompatX & material lib:

implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.2.0-alpha02'

hope to solve your problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Why viewpager2 could solve this problem? Thank you.
1

Create viewPagerAdapter class and paste this code:

public class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFragment(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

After creating adapter, add fragment like this:

ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFragment(new OneToOneChat(), "Chat");
adapter.addFragment(new GroupChatFragment(), "Group Chat");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);

2 Comments

Hi Pang.....i tried your code but its not working.......it does not show even tabs and fragment....anyway thanks for reply
How you define xml for this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.