Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-tablayout

Data not showing after navigation back to the previous tab


I have faced an issue where my data is not longer showing in the fragment when i navigate from one tab to another tab and then coming back to the previous tab.

These are the code for my tablayout and viewpager

tabLayout = (TabLayout) findViewById(R.id.tablayout);
    Todaybooking = (TabItem) findViewById(R.id.Tab1);
    Booking = (TabItem) findViewById(R.id.Tab2);
    viewPager = findViewById(R.id.viewpager);


    pagerAdapter = new FragmentAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
    viewPager.setAdapter(pagerAdapter);


    tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            viewPager.setCurrentItem(tab.getPosition());
            if(tab.getPosition() == 0){
                pagerAdapter.notifyDataSetChanged();

            } else if (tab.getPosition() == 1){
                pagerAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

These are the fragmentadapter i have created

public class FragmentAdapter extends FragmentPagerAdapter {

private int numoftabs;

public FragmentAdapter(@NonNull FragmentManager fm, int numoftabs) {
    super(fm, numoftabs);
    this.numoftabs = numoftabs;
}

@NonNull
@Override
public Fragment getItem(int position) {
    switch(position){
        case 0:
            return new Todaybooking();
        case 1:
            return new Booking();
        default:
            return null;

    }
}

@Override
public int getCount() {
    return numoftabs;
}

@Override
public int getItemPosition(@NonNull Object object) {
    return POSITION_NONE;
}

enter image description here

The fragment on Today's booking is not showing once i click the bookings tab and navigate back to the previous tab.


Solution

  • This is probably because you are returning POSITION_NONE in getItemPosition which is

    Called when the host view is attempting to determine if an item's position has changed. Returns POSITION_UNCHANGED if the position of the given item has not changed or POSITION_NONE if the item is no longer present in the adapter.

    from https://developer.android.com/reference/androidx/viewpager/widget/PagerAdapter#getItemPosition(java.lang.Object)

    So Remove the override of getItemPosition you don't need this normally.

    Because you are indicating that the current instance of each Fragment is no longer in the list of Fragments it will be cause the Fragment to be re-created each time you visit the Tab that holds it.