How to update Fragments in Tablayout? (Viewpager2, FragmentStateAdapter)

1.6k views Asked by At

I create the initial content with the data from an arraylist(i get it from firebase) the data changes every 15 minutes, how do i call a recreation or how do i settext from the mainactivity to the fragments / how do i update the textviews in the fragments (any of those would work please)

i've read a looot of people solving this with getItem but remember i have FragmentStateAdapter i don't have those methods viewPager2.getAdapter().notifyDataSetChanged() does nothing

Overridable Methods in FragmentStateAdapter

and then i thougth how about an interface just to change the text in my textviews but it always calls an error about a null pointer because i understand that the fragment is being "paused" while i don't see it because of the cycle and so and so

Calling a recreation of the viewPager2.setAdapter(new PagerAdapter() works but only when the gods want? and i want something to force it or to be relaiable

(Sincerelly i don't know anymore why am i using the newest viewpager2 and PagerAdapter FragmentStateAdapter as Google suggests) should i try my way around viewpager and all those old tools?

2

There are 2 answers

0
A.Jain On

As per Doc we can update the fragment by calling notifyDatasetChanged() therefore by creating a function(setData) in Adapter and inside which calling notifyDatasetChanged() may be work..like below

 fun addData(data: ArrayList<>) {
    mData = data
    notifyDataSetChanged()
    } 
0
Adam On

I encountered this problem, my solution is: save the fragment instance using WeakReference in adapter, and invoke the method in fragment when needing to update it's data. The code is like this:

public MyAdapter extends FragmentStateAdapter{
    private Map<Integer, WeakReference<MyFragment>> fragmentMap = new HashMap();

    @Override
    public Fragment createFragment(int position) {
        MyFragment fragment=new MyFragment();
        fragmentMap.put(position, new WeakReference<>(fragment));
        return fragment;
    }

    public void updateData(List<String> dataList){
        for (int position : fragmentMap.keySet()) {
            WeakReference<MyFragment> wr = fragmentMap.get(position);
            if (wr != null && wr.get() != null) {
                MyFragment fragment = wr.get();
                fragment.updateData(dataList.get(position));
            }
        }
    }
}

public MyFragment extends Fragment{
    public void updateData(String data){
        ...
    }
}

Now you can invoke updateData(List dataList) on your adapter to update data, and it is using WeakReference to avoid memory leak in the code.