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?
Therefore, in order to pass your data to the Fragment being created, you should use the setArguments() method. This methods gets a bundle, which you store your data in, and stores the Bundle in the arguments. Subsequently, this Bundle can then be retrieved in onCreate() and onCreateView() call backs of the Fragment.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With