Search code examples
androidandroid-fragmentsandroid-viewpagerfragmentandroid-tablayout

refresh adapter in fragment when it is visible


I have two fragments.. I want to refresh my listview adapter adapter.notifyDataSetChanged() in setUserVisibleHint method inside my first Fragment:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if(isVisibleToUser){
        adapter.notifyDataSetChanged();
    }
}

But I get this Exception:

java.lang.NullPointerException at com.androidbelieve.drawerwithswipetabs.FirstFragment.setUserVisibleHint(FirstFragment.java:247) at android.support.v4.app.FragmentPagerAdapter.setPrimaryItem(FragmentPagerAdapter.java:130) at android.support.v4.view.ViewPager.populate(ViewPager.java:1175)

I'm sorry I know a little about Fragments, what is this "setPrimaryItem" !?

This is my Tab Fragment :

public class TabFragment extends Fragment {
View x;
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2 ;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        x =  inflater.inflate(R.layout.tab_layout,null);
        tabLayout = (TabLayout) x.findViewById(R.id.tabs);
        viewPager = (ViewPager) x.findViewById(R.id.viewpager);
        viewPager.setOffscreenPageLimit(2);

    viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
    viewPager.getCurrentItem();
    viewPager.addOnPageChangeListener(new OnPageChangeListener() {


        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });


    tabLayout.post(new Runnable() {
        @Override
        public void run() {
                tabLayout.setupWithViewPager(viewPager);
               }
    });

    return x;
}

class MyAdapter extends FragmentPagerAdapter{
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }


    @Override
    public Fragment getItem(int position)
    {
      switch (position){
          case 0 : return new FirstFragment();
          case 1 : return new ZZZFavorites();
      }
    return null;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position){
            case 0 :
                return "Online";
            case 1 :
                return "Favorites";
        }
            return null;
      }
    }
}

Solution

  • Your adapter is null. Perform null-check before accessing it.

    if (isVisibleToUser && adapter != null) {
        adapter.notifyDataSetChanged();
    }