Android passing object from Activity to Fragment

We can easily pass primitive data types between two activity or two fragment. But we need a little bit of extra work to pass an object between activity and fragment. Here, we will see how to pass an object from activity to fragment using google Gson library. Note that same concept will work if you want to pass object between two activities with minor change in code.

1) Add the following dependency in your build.gradle(app)

2) Create a new class

3) Create a new java class

4) Create a new layout file fragment_user.xml


5) If you don’t have class, then create it

6) Create a layout file activity_main.xml for MainActivity


7) In your MainActivity.class, add the following function to pass an object

8) In your UserFragment.class, add the following code to deserialize an object

9) Whole code

Download the source code

2 thoughts on “Android passing object from Activity to Fragment”

Leave a Reply

Your email address will not be published. Required fields are marked *