D
D
dendead2020-08-02 19:25:58
Java
dendead, 2020-08-02 19:25:58

How to send data from Activity to Fragment with ViewPager2 connected?

Hello!
I am trying to send data from MainActivity to one of the fragments created with ViewPager2.

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);
 
    ViewPager2 viewPager = findViewById(R.id.viewPager);
    MainPagerAdapter pagerAdapter = new MainPagerAdapter(this);
    viewPager.setAdapter(pagerAdapter);
}


MainPagerAdapter:

public class MainPagerAdapter extends FragmentStateAdapter
{
    public MainPagerAdapter(@NonNull FragmentActivity fragmentActivity)
    {
        super(fragmentActivity);
    }
 
    @NonNull
    @Override
    public Fragment createFragment(int position)
    {
        switch (position)
        {
            case 0:
                return new Fragment1();
            case 1:
                return new Fragment2();
            default:
                return new Fragment3();
        }
    }
 
    @Override
    public int getItemCount()
    {
        return 3;
    }
}


I send data from MainActivity like this:

Fragment1 fragment1 = new Fragment1();
 
Bundle bundle = new Bundle();
bundle.putInt("1", 1);
fragment1.setArguments(bundle);


And trying to get them in Fragment:

Bundle bundle = this.getArguments();
if (bundle != null)
{
    int i = bundle.getInt("1", 0);
    Log.d(Constants.LOG_TAG, "" + i);
}


But an empty bundle always arrives, because the fragment is only created when the Viewpager flips through it.
How do I send data to the Fragment while the MainActivity is being created?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2020-08-04
@dendead

At the time the activity is created, the fragment does not yet exist. You, judging by the code, created it, filled it with data, and then just threw it away. The pager has created a new fragment for itself.
One of the ways here is to make a certain repository with data, where the activity will add them, and the fragment will take it from there when it needs the data. Store the repository in an activity or in a DI graph.
Another easier way is to use the adapter as intended. He, as planned, adapts (turns) the data into fragments. Pass your data from the activity to the adapter, and when creating a fragment in the adapter, fill it with this data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question