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 User.java

User.java

3) Create a new java class UserFragment.java

UserFragment.java

4) Create a new layout file fragment_user.xml

fragment_user.xml

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

MainActivity.java

6) Create a layout file activity_main.xml for MainActivity

activity_main.xml

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

MainActivity.java

UserFragment.java

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 *