proy31 proy31 - 1 year ago 94
Android Question

Accessing data of parent activity from a fragment

What is the best way to access data members of an activity from its fragment
Some ways which I know include -

  1. Create an interface in the Fragment which the Activity will implement. The interface will have the methods to access data members of the Activity.

  2. Directly access using ((Activity)getActivity).getXXX() from the fragment.

  3. Pass the data members or custom parcelable class to newInstance method of the fragment and set the fragment arguments as the class for e.g. -

    Bundle args = new Bundle();

    args.putInt("num", num);


    and later we can get the arguments using getArguments()

Which method is the best and what are the drawbacks of each?

Answer Source

Actually the combination of the first and third method is the best. The second one should be avoided at all cost since this strongly couples the Fragment to a specific Activity. This will defeat one of the main advantages of Fragments namely being able to use it in different Activities (plug and play).

As for the first and third method. - The first one is how you will usually communicate from the Fragment to your Activity. - The third one is how you'll usually instantiate your Fragment while passing data to it from your Activity. When you already have an instance of your Fragment running you'll have to fall back on your first method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download