Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Bundle with Fragment Transaction

Tags:

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?

like image 712
TheLettuceMaster Avatar asked Mar 11 '13 00:03

TheLettuceMaster


People also ask

How do I pass bundles in fragment?

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.

How can we send data from one fragment to another?

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

like image 127
Tushar Avatar answered Sep 21 '22 09:09

Tushar