Sending Bundle with Fragment Transaction

TheLettuceMaster picture TheLettuceMaster · Mar 11, 2013 · Viewed 21.5k times · Source

Here is my code that is not working:

// Sending bundle this way:

        String topUser = String.valueOf(scores.get(arg2));

        Bundle data = new Bundle();
        data.putString("userprofile", topUser);

        FragmentTransaction t = getActivity().getSupportFragmentManager()
                .beginTransaction();
        SherlockListFragment mFrag = new ProfileFragment();
        mFrag.setArguments(data);
        t.replace(R.id.main_frag, mFrag);
        t.commit();

// Retrieving this way:

        Bundle extras = getActivity().getIntent().getExtras();
        userName = extras.getString("userprofile");

Basically, the data isn't received. Am I on the right track or is there a better way of doing this?

Answer

Tushar picture Tushar · Mar 11, 2013

You should be using the getArguments() method of the Fragment class. So put something like the following inside your Fragment:

Bundle extras = getArguments();

Reference: http://developer.android.com/reference/android/app/Fragment.html#getArguments()