14

I am building a tab interface using Action bar and fragment. I would need assistance in sending data from container activity to the fragment.

To elaborate, I have job object in container activty. And I have created few tabs based on the information in job object (like company details, experience details etc). I need to pass the job object to these fragments so that it can display respective information.

I have created container activity and tab fragments. I would need an example on how to pass the object across them. I cannot use intent.putExtra. Can I access parent container's object from fragment?

Any help shall be appreciated.

Thanks.

user1829067
  • 143
  • 1
  • 1
  • 6
  • 1
    have You checked http://developer.android.com/training/basics/fragments/communicating.html ? – sandrstar Dec 07 '12 at 08:41
  • @sandrstar included the link you also posted in my answer. – LonWolf Dec 07 '12 at 08:49
  • Possible duplicate of [Android: how can fragment take a global variable of Activity](http://stackoverflow.com/questions/12364434/android-how-can-fragment-take-a-global-variable-of-activity) – Shirish Herwade May 10 '17 at 07:14

2 Answers2

50

Make the method in your activity, e.g getJob that will return the Job object and its information

MyActivity extends Activity{
Job mJob;

public Job getJob(){
   return this.mJob;
 }
}

then in your Fragment you do this:

MyFragment extends Fragment{

@Override
public void onActivityCreated(){
  super.onActivityCreated();
  ((MyActivity)this.getActivity()).getJob();
 }
}

use getActivity and the method getJob(); to get the object

DevC
  • 6,982
  • 9
  • 45
  • 80
Artem Zelinskiy
  • 2,201
  • 16
  • 19
2

There are multiple ways of achieving this.

  1. Make a static variable to hold your data and access that data from inside the fragments - this is the most fast but it creates bad design patterns if used improperly.
  2. A way of Fragment-to-Fragment communication possible through the parent Activity is posted here: http://developer.android.com/training/basics/fragments/communicating.html You can use the sample code to just do a Activity - Fragment data send.
  3. The top voted answer here: Accessing instance of the parent activity? mentions a way to avoid using static data (1.) and contains source code examples using ActivityGroup

"If you need access to some values in your First activity without making a static reference to it, you could consider putting your activities in an ActivityGroup."

What you choose is your preference, these are just a few options!


Edit: I'm not sure if number 3 will work with fragments since I haven't tested a method similar to it, the example is Activity - Activity communication.
Community
  • 1
  • 1
LonWolf
  • 132
  • 4