Android Pass Data from Activity to Fragment

Android Pass Data from Activity to Fragment

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 :

  1. Android Intent.
  2. StartActivityForResult.

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:

  • Bundle – Bundle is a mapping from String values to various Parcelable types.
We can pass int, float or any data type. This is same as we pass data in Intent.

  • SetArguments – setArguments() is a method to set bundle data over fragment. This bundle data will pass with the fragment.
Note: The above two steps are done inside Activity.
Now, steps for how to retrieve data inside fragment.

  • GetArguments – getArguments() method used for getting passed data from activity to fragment. In this we have to retrieve data with particular key value.

VIDEO DEMO

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.

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.

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.

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.

6. Finally come to your MainActivity.java and add the following code. In this code i am passing data by using setArguments() to fragment.

7. Finally, all done  –  run the app and you will get the output as shown in video.

Thanks. :)

Download Source Code – >

COMMENTS (1)
Reply

Working for me! Thanks a lot !

Leave a Comment

Comment (required)

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">

Name (required)
Email (required)