jos jos - 25 days ago 5
Android Question

ViewPager and RecyclerView extrange behaviour

I have a

Fragment
with a
ViewPager
which handles three
Fragment
s. The first of them contains a
RecyclerView
. Here is some code:

FragmentViewPager

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_player_view_pager, container, false);

ViewPager vpPager = (ViewPager) view.findViewById(R.id.playerViewPager);
adapterViewPager = new PlayerPagerAdapter(getFragmentManager());
vpPager.setAdapter(adapterViewPager);

return view;
}


FragmentPagerAdapter

// Returns the fragment to display for that page
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return FirstFragment.newInstance("0", "Page # 1");
case 1:
return SecondFragment.newInstance("1", "Page # 2");
case 2:
return ThirdFragment.newInstance("2", "Page # 3");
default:
return null;
}
}


FirstFragment:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);

recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
adapter = new FragmentAdapter(getActivity(), myList);

recyclerView.setItemAnimator(new SlideInUpAnimator(new OvershootInterpolator(1f)));
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 2));

recyclerView.setAdapter(adapter);

loadData();

return view;
}


And
loadData
method is an API call through
AsyncTask
which populates the adapter. This is the onPostExecute method:

myList = (ArrayList<>) result;
adapter.notifyDataSetChanged();


The problem is when I first instantiate the
ViewPager
nothing is showed in the first
Fragment
even the API call and the
notifyDataSetChanged()
method are called. But if I scroll between the other Fragments and the
FirstFragment
is recreated by the
ViewPager
, then the data is shown.

Do you have any idea what is happening here?

Answer

After getting response update data myList (ArrayList<>) of FragmentAdapter, by any method created by you and then call notifyDataSetChanged() method of Adapter.

myList = (ArrayList<>) result; This initialization is not reflect on FragmentAdapter ArrayList

Comments