Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : Accessing container activity object from fragment using putExtra?

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.

like image 243
user1829067 Avatar asked Dec 07 '12 08:12

user1829067


People also ask

How do you call an activity inside a fragment?

Best way of calling Activity from Fragment class is that make interface in Fragment and add onItemClick() method in that interface. Now implement it to your first activity and call second activity from there.

Can we navigate from activity to fragment?

If you want to go back from Activity to Fragment. This is very simple just override onBackPressed() in your activity and call onBackPressed where you want.

How can we interface between fragments and activities?

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() lifecycle method and can then call the Interface methods to communicate with the Activity.


1 Answers

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

like image 105
Artem Zelinskiy Avatar answered Oct 14 '22 07:10

Artem Zelinskiy