Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass custom class to Fragment

I have a custom class called Data which contains all the data. The main activity creates two fragments. I have a field in the main activity like this:

private Data data = new Data();

The fragments are created with this method:

private ArrayList<Fragment> getFragments() {
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();
    fragments.add(new fragment_one());
    fragments.add(new fragment_two());
    return fragments;
}

I need to pass the data field to the fragments, so the fragments can acces the methods of Data.

I tried by creating a bundle, but I can't pass a custom class. What can I do?

like image 603
stefana Avatar asked Dec 20 '22 19:12

stefana


1 Answers

Bundles can accept custom classes, if they implement either Parcelable or Serializable, Parcelable is faster but more work to implement and Serializable is easier to implement, but slower.

Then you can do this:

Bundle bundle = new Bundle();
bundle.putSerializable("MyData", data);
fragment_one.setArguments(bundle);

Now fragment_one will have access to data in it's onCreate(Bundle bundleHoldingData) method.

Another option is to have a public setter in your fragment that takes in data. Benefit of this is you don't have to wait till data is ready to add the fragment.

like image 135
quinnjn Avatar answered Dec 30 '22 11:12

quinnjn