5

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?

stefana
  • 2,606
  • 3
  • 29
  • 47

5 Answers5

6

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.

quinnjn
  • 623
  • 7
  • 10
4

Data needs to either implement Parcelable or Serializable.

You can then either use bundle.putParcelable() or bundle.putSerializable() to pass the data to both fragments via the setArguments() method.

Patrick Dattilio
  • 1,814
  • 3
  • 21
  • 35
1

You should not pass references to fragments, all your data should be passed using setArguments (unless your fragment is retained). The reason is that android might destroy your fragment during configuration change, and recreate it during activity creation.

So you should either pass your data inside setArguments, or give access to it using singleton class, ie. application class.

[edit] - havent tried this myself but you can find online tools to make your data class parcelable, here is one: http://devk.it/proj/parcelabler/

marcinj
  • 48,511
  • 9
  • 79
  • 100
0

You can set a static object depending how much data you keep and careful with the memory leaks. That way you can reach it within the fragments. But making the data parcelable and pass it with the bundle is always a better choice.

Barışcan Kayaoğlu
  • 1,294
  • 3
  • 14
  • 35
0

One option is to provide an accessor for the data on the Activity class. Then, in your fragment, you call getActivity(), cast it to the derived type, and get the data, as needed.

This of course creates a dependency from your fragment to the activity, but if it's not meant to be a generic, re-usable fragment, it would be very simple and straightforward to implement and means you can get a reference to the current Activity data and not a copy like the Bundle / Parcelable / Serializable strategy would.

dominicoder
  • 9,338
  • 1
  • 26
  • 32