Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 202
TheLettuceMaster Avatar asked Jul 09 '12 00:07

TheLettuceMaster


People also ask

How do I get intent extra in fragment?

If you want get intent data, you have to call Fragment's method getArguments() , which returns Bundle with extras. Show activity on this post.

How can Intent from fragment to activity in Android?

Intent intent = new Intent(getActivity(), AnotherActivity. class); startActivity(intent); Currently you're using MainActivity. class in a place that requires a context object.

How do I pass data from fragment to fragment in Kotlin?

Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.


1 Answers

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.

like image 83
meeeee Avatar answered Oct 10 '22 16:10

meeeee