Where/How to getIntent().getExtras() in an Android Fragment?

TheLettuceMaster picture TheLettuceMaster · Jul 9, 2012 · Viewed 142.5k times · Source

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?)

Answer

meeeee picture meeeee · Feb 7, 2013

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.