Angel F.
Angel F.

Reputation: 176

Pass parameter from activity to fragment

I have an activity that calls to a web service and I want to pass these result to a fragment. Obviously the web service is invoked by an AsyncTask, so the fragment is loaded before getting result.

How can I pass this paramteter from activity's AsyncTask to fragment when is received?

Upvotes: 1

Views: 820

Answers (3)

Akhil Jayakumar
Akhil Jayakumar

Reputation: 2312

Set bundle in your fragment.

Bundle args = new Bundle();
args.putInt("id",value);    
Fragment newFragment = new Fragment();
newFragment.setArguments(args);

In your fragment get the bundle as

Bundle b = getArguments();
String s = b.getInt("id");

Upvotes: 1

Moonbloom
Moonbloom

Reputation: 7918

You could move the AsyncTask into the fragment.

But if you wish to keep your current set up, you should save the Fragment reference when you initialize it, and create a public function in the fragment that takes the new data as a parameter.

So the activity code could look like this:

MyFragment fragment = new MyFragment();
getFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();

and then you could call:

fragment.updateData(myNewData);

Just make sure to do the appropriate null-checks, just to be safe.

Upvotes: 0

localhorst
localhorst

Reputation: 365

You can implement a method inside your Fragment and call it when needed. For bidirectional communication between an Activity and a Fragment see http://developer.android.com/training/basics/fragments/communicating.html

Upvotes: 1

Related Questions