This question already has an answer here:
- Android: Pass data(extras) to a fragment 4 answers
With Activities, I used to do this:
In Activity 1:
Intent i = new Intent(getApplicationContext(), MyFragmentActivity.class);
i.putExtra("name", items.get(arg2));
i.putExtra("category", Category);
startActivity(i);
In Activity 2:
Item = getIntent().getExtras().getString("name");
How do you do this using Fragments? I am using the compatibility library v4 also.
Does it go in the FragmentActivity? Or the actual Fragment? And Which Method does it go in? onCreate? onCreateView? another?
And can I see example code please?
EDIT: It is worth noting I am trying to keep Activity 1 as an Activity (or actually ListActivity where I am passing the intent of the listitem when clicked) and then pass to a set of tabbed-fragments (through a Fragment Activity) and I need either tab to be able to get the extras. (I hope this is possible?)
you can still use
in the
fragment
, you just need callgetActivity()
first:This saves you having to write some code.
What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an
Intent
in anActivity
and then pass any extra data to fragments by instantiating them with arguments.There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using
FragmentActivity
andFragment
from the support library.You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:
In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called
newInstance
in the examples given by Google. There actually is anewInstance
method inDetailsFragment
, so I'm unsure why it isn't used in the snippet above...Anyways, all extras provided as argument upon creating the fragment, will be available by calling
getArguments()
. Since this returns aBundle
, its usage is similar to that of the extras in anActivity
.