0

I want to send some Data from a fragment to a new fragment. I know this can be done with a bundle but I don't know how to use them, especially not with my own objects.

I replace my old fragment with a new one like this:

Fragment newFragment = new SecondFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, newFragment);
transaction.addToBackStack("saveState");
transaction.commit();

So now I want to send this Data to the "newFragment".

private List<MyObject> objectList;

How can I put this objectList to a new Bundle?

EDIT:

And also, how can I send the bundle from my old fragment to the newFragment?

RyuZz
  • 581
  • 8
  • 30
  • 2
    Please read: http://developer.android.com/training/basics/fragments/communicating.html – Jared Burrows Feb 05 '15 at 17:02
  • Well now I know how to pass the data with the host activity to the new fragment, but I still does not know how to put the objectList to the bundle? – RyuZz Feb 05 '15 at 17:14
  • Pass through constructor? Pass via interface? Did you even read information the link provided? – Jared Burrows Feb 05 '15 at 17:19
  • Well it's not strongly recommended to create a non-default constructor in a subclass, so sending data through constructor is not even the best solution. So the given information on the site is to use setArgument(Bundle) but there is still the problem that I don't know how to put the list in the bundle and the site don't give me this information. – RyuZz Feb 05 '15 at 17:29
  • Once again, please read what I said in my comment and the link. To make things more clear, here is an example: http://stackoverflow.com/a/9977370/950427. – Jared Burrows Feb 05 '15 at 17:32

2 Answers2

1

Your custom Object must implement Parcelable. Parcelable is a way to tell Android how the reconstruct custom Objects when passed through a Bundle. http://developer.android.com/reference/android/os/Parcelable.html

Once your Object implements Parcelable, you can put your list in the Bundle using putParcelableArrayList(String key, ArrayList value)

It is a bit tricky the first time, but you'll get there =) There is plenty of tutorials available.

JDenais
  • 2,956
  • 2
  • 21
  • 30
0

Use GSON library:

GIGAMOLE
  • 1,274
  • 1
  • 11
  • 17