2

I have an activity where the user press a button and then is send to a fragment, but I wish to pass an extra for the use of the fragment:

activity A(where is the button):

public OnClickListener publish = new OnClickListener(){

       @Override
       public void onClick(View v) {


           Intent intent = new Intent(v.getContext(),ActivityB.class);
           intent.putExtra("friendIdRowID", rowID);
           startActivity(intent);


       }
   };

Activity B is loading the fragment(where I wish to retrieve the extra "friendIdRowID"), the fragment:

 @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.activity_main2, container, false);

            Bundle extras = getActivity().getIntent().getExtras();

        if (extras != null)
        {

            String myString = extras.getString("friendIdRowID");
}
        }

But it is not working, what can I do to pass and retrieve the extra? thanks.

user2580401
  • 1,840
  • 9
  • 28
  • 35

1 Answers1

8

You need to use the setArguments() method of Fragment to pass information into your fragment. In the activity that creates the fragment, do something like this:

YourFragment f = new YourFragment();
Bundle args = new Bundle();
args.putString("friendIDRowID", getIntent().getExtras().getString("friendIDRowID"));
f.setArguments(args);
transaction.add(R.id.fragment_container, f, "tag").commit();

Then, override the onCreate() method of your Fragment and do the following:

Bundle args = getArguments();
String myString = args.getString("friendIdRowID");

Like extras for an Activity, you can add as many things to your arguments bundle as you wish. Hope this helps!

Nathan Walters
  • 4,116
  • 4
  • 23
  • 37