Android : Accessing container activity object from fragment using putExtra?

user1829067 picture user1829067 · Dec 7, 2012 · Viewed 21.1k times · Source

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.

Answer

Artem Zelinskiy picture Artem Zelinskiy · Dec 7, 2012

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