I have a tab layout with a ViewPager having 3 fragments. Data inside these fragments is populated by recyclerview. I have also implemented swipe to refresh layout in this fragment.
When I pull to refresh the 'PostTab', I want to restart/reload the fragment so as to fetch the new set of data from the server. I am not able to do so.
I know there are tons of answers around this topic but I guess this is the case of having too much information and thus after trying many different things I am not able to do it.
MainActivity file contains FragmentPagerAdapter to make the fragments
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new CategoryTab();
case 1:
return new PostTab();
case 2:
return new VideoTab();
default:
return null;
}
}
@Override
public int getCount() {
return 3;
}
@Override
public CharSequence getPageTitle ( int position){
switch (position) {
case 0:
return "Tab1 Working";
case 1:
return "Tab2 Working";
case 2:
return "Tab3 Working";
}
return null;
}
}
The refresh layout is present inside the PostTab fragment
PostTab.java
public class PostTab extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.post_tab, container, false);
// Get data from server
//set recycler adapter
//Scroll listener to load more data
//Load more data on scroll
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
refreshItems();
}
});
return view;
}
public void refreshItems(){
final android.support.v4.app.FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
fragmentTransaction.detach(this);
fragmentTransaction.attach(this);
fragmentTransaction.commit();
}
}
}
The above code loads the new data properly but then my app crashes. My guess is that this code does not fully restart the fragment by calling onCreateView method again.
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder
If I change the code to below, then fragment goes blank (Previously loaded data also goes away).
fragmentTransaction.remove(this);
fragmentTransaction.attact(this);
How do I use remove & add? As I haven't set the tag earlier my app crashes with the whatever tag I set here.
fragmentTransaction.remove(this);
fragmentTransaction.add(this,"Tag");
Can 'replace' be helpful? As per my understanding it will replace all fragments. I just need to reload 1 out of 3 fragments.
I tried to follow this answer but I don't know the fragment tag as I haven't set it.