0

My code is as follows

    private List<SdkBaseFragment> fragments;

    public HomeFragmentAdapter(FragmentActivity fragmentActivity, List<SdkBaseFragment> fragments)
    {
        super(fragmentActivity);
        this.fragments = fragments;
    }

    @Override
    public Fragment createFragment(int position)
    {
        return fragments.get(position);
    }

    @Override
    public int getItemCount()
    {
        return fragments != null ? fragments.size() : 0;
    }

I read the FragmentStateAdapter source code because createFragment returned an empty fragment, but when I created the HomeFragmentAdapter, I passed in the created fragment list. It should not be empty. Under what circumstances will the data in the List be recycled but the List will not be recycled? What kind of situation will find this problem? It is difficult for me to repeat this problem

The exception information is as follows

java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.fragment.app.Fragment.setInitialSavedState(androidx.fragment.app.Fragment$SavedState)' on a null object reference at androidx.viewpager2.adapter.FragmentStateAdapter.ensureFragment(SourceFile:269) at androidx.viewpager2.adapter.FragmentStateAdapter.onBindViewHolder(SourceFile:175) at androidx.viewpager2.adapter.FragmentStateAdapter.onBindViewHolder(SourceFile:67) at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(SourceFile:7254) at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(SourceFile:7337) at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(SourceFile:6194) at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(SourceFile:6460) at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(SourceFile:6300) at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(SourceFile:6296) at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(SourceFile:2330) at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(SourceFile:1631) at androidx.recyclerview.widget.LinearLayoutManager.fill(SourceFile:1591) at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(SourceFile:668) at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(SourceFile:4309) at androidx.recyclerview.widget.RecyclerView.dispatchLayout(SourceFile:4026) at androidx.recyclerview.widget.RecyclerView.onLayout(SourceFile:4578) at android.view.View.layout(View.java:21973) at android.view.ViewGroup.layout(ViewGroup.java:6263) at androidx.viewpager2.widget.ViewPager2.onLayout(SourceFile:527) .........

I have modified the code now. I don't know if I can solve this problem

@Override public Fragment createFragment(int position) { return WebFragment.newInst("xxx"); }

0 Answers0