-1

I would like to pass an object from an activity to a fragment. I know how to pass the data but do not know which type of bundle i should use?

UPdate

In other words, I have an object of type mqttAndroidClient and that object i want to pass from my activity to a fragment through a bundle. Which bundle type I should use?

rmaik
  • 1,076
  • 3
  • 15
  • 48
  • possible duplicate of [How to create Serializable object and pass to bundle.putSerializable(key, value)](http://stackoverflow.com/questions/27122149/how-to-create-serializable-object-and-pass-to-bundle-putserializablekey-value) – spacifici Nov 25 '14 at 10:30

2 Answers2

0

you should use something like this :

make your custom class that contains your desired data to be passed and extend from Serializable or Parcelable and put your object as extra to your Bundle object and set Bundle as an argument to your Fragment.

in your Activity

...
Fragment fragment = new YourFragment();
Bundle bundle = new Bundle();
bundle.putString("data", "yourData");
fragment.setArguments(bundle);
...

in your Fragment

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    String data = getArguments().getString("data");    
    ...
}
Mohammad Rahchamani
  • 5,002
  • 1
  • 26
  • 36
  • thanks, but i know how to pass the data, but i do not know which type of bundles i should use to pass an object. – rmaik Nov 24 '14 at 21:33
0

For relatively simple object data types, you shouldn't need a bundle at all. When you override onCreate() in the fragment that uses the argument, simply add a line of code that fetches the data from the intent.

For example, if you're passing an integer, the line would be:

intvar = (int)getActivity().getIntent().getInt(SOME_IDENTIFIER); 

where SOME_IDENTIFIER is a constant that's common to both the activity and the fragment. (It would look something like "com.yourpackage.yourapp.some_identifier."

  • If your class uses only primitive data types, you can use a Parcel in place of a bundle. See the answers in http://stackoverflow.com/questions/5621132/passing-custom-objects-between-activities – Brogrammer Dude Nov 24 '14 at 21:45