FragmentStateAdapter with ViewPager2 showing incorrect fragment

293 views Asked by At

My app has an activity that displays a list of items using a RecyclerView. When a list item is selected, the UUID of the model object associated with that list item is sent as an intent extra to another activity that has a ViewPager2 adapter in its layout.

I created an adapter using the FragmentStateAdapter class and attached the adapter to the ViewPager2 widget. For some reason I get the wrong fragment displayed even though the correct UUID is sent to the ViewPager2 Activity and the correct item position is used in the FragmentStateAdapter#createFragment method.

The correct UUID is also sent to the created fragment and the correct model data is set on the widgets of the created fragment.

I use a singleton called CrimeLab to store a list of Crime objects as well as methods to return a model object by its UUID and to return the stored list of Crime objects. Below is the code for the activity that contains a ViewPager2 widget and implements the FragmentStateAdapter.

public class CrimePagerActivity extends AppCompatActivity{

private static final String EXTRA_ID = "com.bignerdranch.android.extra_id";

private ViewPager2 crimePager;
private CrimePagerAdapter adapter;
private List<Crime> crimes;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_crime_pager);

    crimes = CrimeLab.get(this).getCrimes();

    crimePager = findViewById(R.id.crime_pager);
    UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_ID);
    Crime crime = CrimeLab.get(this).getCrime(crimeId);
   
    adapter = new CrimePagerAdapter(this);
    crimePager.setAdapter(adapter);
    crimePager.setCurrentItem(crimes.indexOf(crime));
    
}

private class CrimePagerAdapter extends FragmentStateAdapter {

    public CrimePagerAdapter(@NonNull FragmentActivity fragmentActivity) {
        super(fragmentActivity);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        Crime crime = crimes.get(position);
        return CrimeFragment.newInstance(crime.getId());

    }

    @Override
    public int getItemCount() {
        return crimes.size();
    }
}

public static Intent createIntent(Context context, UUID crimeId) 
{
    Intent intent = new Intent(context, CrimePagerActivity.class);
    intent.putExtra(EXTRA_ID, crimeId);

    return intent;
}
}
0

There are 0 answers