Which bundle should be used to pass an object

64 views Asked by At

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?

2

There are 2 answers

1
Mohammad Rahchamani On

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");    
    ...
}
1
Brogrammer Dude On

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."