Earlier we had learn how to pass data from one activity to another and get back data from another activity. You can find both tutorials here :
Today we are going to learn how to pass data from Activity to Fragment. Before starting this tutorial just go through Fragments Tutorial if you are new to Fragments. For passing data from activity to fragment you can follow some steps given below:
1 2 |
Bundle data = new Bundle();//create bundle instance data.putString("key_value", "String to pass");//put string to pass with a key value |
We can pass int, float or any data type. This is same as we pass data in Intent.
1 |
fragmentName.setArguments(data);//Set bundle data to fragment |
Note: The above two steps are done inside Activity.
Now, steps for how to retrieve data inside fragment.
1 |
String getArgument = getArguments().getString("key_value");//Get pass data with its key value |
Now, Let’s start with example.
1. Create a new project in Android Studio by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Now create a xml layout naming activity_main.xml and add the following code. In this layout i had taken two Button one for Simple Fragment and another for Argument Fragment and there is a FrameLayout for holding fragment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:id="@+id/setDefaultFragment" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="Default Fragment" /> <Button android:id="@+id/setArgumentFragment" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:text="Argument Fragment" /> </LinearLayout> <!-- Frame Layout for placing Fragments --> <FrameLayout android:id="@+id/fragmentContainer" android:layout_width="fill_parent" android:layout_height="fill_parent"> </FrameLayout> </LinearLayout> |
3. For fragment UI design create new layout xml file naming fragmentlayout.xml and add the following code. In this layout i had taken one TextView whose text is “Default Text” by default which gonna change while replacing Argument Fragment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#ff00" android:gravity="center" android:orientation="vertical"> <TextView android:id="@+id/fragmentText" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:text="Default Text" android:textColor="#ffffff" android:textSize="20sp" /> </LinearLayout> |
4. Since we are working on two fragment so create two new java classes. First create DefaultFragment.java and add the following code. In this code i had just inflate the layout.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
package com.fragmentsetargument_demo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; /** * Created by SONU on 07/10/15. */ public class DefaultFragment extends Fragment { //Simple Fragment public DefaultFragment() { } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragmentlayout, container, false); } } |
5. Now create a new java class for second fragment naming ArgumentFragment.java and add the following code. In this code i am retrieving passed data by using getArguments() method with particular key value and setting over TextView.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.fragmentsetargument_demo; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * Created by SONU on 07/10/15. */ public class ArgumentFragment extends Fragment { public ArgumentFragment() { } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragmentlayout, container, false);//Inflate Layout TextView text = (TextView) view.findViewById(R.id.fragmentText);//Find textview Id //Get Argument that passed from activity in "data" key value String getArgument = getArguments().getString("data"); text.setText(getArgument);//set string over textview return view;//return view } } |
6. Finally come to your MainActivity.java and add the following code. In this code i am passing data by using setArguments() to fragment.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
package com.fragmentsetargument_demo; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private static Button defaultFragment, argumentFragment; private static FragmentManager fragmentManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fragmentManager = getSupportFragmentManager();//Get Fragment Manager //Find Ids defaultFragment = (Button) findViewById(R.id.setDefaultFragment); argumentFragment = (Button) findViewById(R.id.setArgumentFragment); //Implement Click Listener defaultFragment.setOnClickListener(this); argumentFragment.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.setDefaultFragment: //Replace default fragment fragmentManager.beginTransaction().replace(R.id.fragmentContainer, new DefaultFragment()).commit(); break; case R.id.setArgumentFragment: Fragment argumentFragment = new ArgumentFragment();//Get Fragment Instance Bundle data = new Bundle();//Use bundle to pass data data.putString("data", "This is Argument Fragment");//put string, int, etc in bundle with a key value argumentFragment.setArguments(data);//Finally set argument bundle to fragment fragmentManager.beginTransaction().replace(R.id.fragmentContainer, argumentFragment).commit();//now replace the argument fragment /** Note: If you are passing argument in fragment then don't use below code always replace fragment instance where we had set bundle as argument as we had done above else it will give exception **/ // fragmentManager.beginTransaction().replace(R.id.fragmentContainer, new ArgumentFragment()).commit(); break; } } } |
7. Finally, all done – run the app and you will get the output as shown in video.
Thanks.
Subscribe to us and get the latest news.
25 Comments
MJ_IT
Friday, September 16th, 2016Working for me! Thanks a lot !
fajarra
Monday, February 6th, 2017Its work. How about passing data from fragment to activity ?,
Dr. Droid
Monday, February 6th, 2017Hi Fajarra,
Its same as like we use to send data from one activity to another.
Intent in = new Intent(getActivity(),Activity.class);
in.putExtra(key,value);
startActivity(in);
Thanks
Shreya Singh
Friday, June 23rd, 2017When I am doing the same with int my app is carshing, can u plz help me out?
Dr. Droid
Friday, June 23rd, 2017Hi Shreya,
Can you share your code with me , so that i can understand where exactly you are doing wrong.
Thanks
nitish sharma
Tuesday, November 14th, 2017how to send data from fragment to activity ?
Dr. Droid
Tuesday, November 14th, 2017Hi Nitish,
Use the below code to send data to activity from fragment :
Intent in = new Intent(getActivity(),ActivityName.class);
in.putExtra(“message”,message);
startActivity(in);
Thanks
vips
Tuesday, December 12th, 2017great one bro works fine
Andrea
Friday, December 15th, 2017Do you know what is the best way to send and fetch data between fragments?
If I have a list of posts for example and I want to show the full post in another fragment when I click on it, what is the best way to do that, send all data from one fragment to another, (title, image url, text) or send just the ID and fetch the rest inside the new fragment?
Regards,
Andrea
Dr. Droid
Saturday, December 16th, 2017Hi Andrea,
To send data from one Fragment to another Fragment you have to use the same thing that i have done in this above article by passing data from Activity to Fragment.
So you can use the same code and put in your Fragment from where you want to pass data to another Fragment.
Thanks
Shivani Verma
Monday, February 26th, 2018sir i have an issue i am getting a list of songs in json response and there is a parameter inside it song category which includes different categories like hot tracks,trending etc and now i have to display them in different fragments according to their respective categories and i dont know hoe to achieve that can you please help me out
Dr. Droid
Wednesday, February 28th, 2018Hi Shivani
Are you able to parse JSON data?
How you want to show your categories and songs? Using tabs or some other designs?
Thanks
ADAM
Thursday, June 21st, 2018i have a list of books which i used parcelable to pass it to another fragment from my class. i get getArguments as null in my fragment when i try to retrieve it , causing an NPE and crashes my app. what should i do ?
Dr. Droid
Sunday, June 24th, 2018Hi Adam,
Can you share your code to my mail id. So that i can see what is the issue.
Thanks
akash
Thursday, October 4th, 2018i am getting arguments null
Dr. Droid
Monday, October 8th, 2018Hi Akash,
Can you share your error logs and code line where you are getting exception. May be you are doing some wrong.
Thanks
Claudio
Sunday, March 31st, 2019Thanks for sharing your knowledge. I was wondering how could you pass an array of objects as argument, but it worked fine…
Best regards from Brazil!
Romelo Lora
Thursday, November 7th, 2019hi how can I move the data from activity to fragment
Dr. Droid
Thursday, November 7th, 2019Hi Romelo,
You have to use the same way which is shown in the post. I am posting code snippet below:
Fragment argumentFragment = new ArgumentFragment();//Get Fragment Instance
Bundle data = new Bundle();//Use bundle to pass data
data.putString(“data”, “This is Argument Fragment”);//put string, int, etc in bundle with a key value
argumentFragment.setArguments(data);//Finally set argument bundle to fragment
fragmentManager.beginTransaction().replace(R.id.fragmentContainer, argumentFragment).commit();//now replace the argument fragment
Thanks
newbe
Friday, November 8th, 2019how can i go back from an AppCompatActivity to Fragments
Dr. Droid
Saturday, November 9th, 2019Hi Newbe,
For your question there are two situations:
1. If the fragment is in the same Activity: Then you have to use the fragment transaction.
2. If the fragment is in different Activity: Then you have to use Intent and once you go to different activity there in onCreate method you have to replace/add respective fragment.
Let me know if you have any other case or situation.
Thanks
Jayant
Tuesday, December 24th, 2019Can you please tell this for Kotlin
Dr. Droid
Wednesday, December 25th, 2019Hi Jayant,
Please check this link: https://stackoverflow.com/questions/53964718/passing-a-value-from-activity-to-fragment-in-kotlin.
Thanks
Chen Vincent
Thursday, February 20th, 2020Hi Dr. Droid: I am using navigation drawer model in my APP. And I need share the data from MainActivity to other fragments. How can I do it? May I try to use the example you posted to this scenario? Thank you for your reply.
Dr. Droid
Thursday, February 20th, 2020Hi Chen,
Yes, you can use this example to share data between activity and fragment.
Thanks