Looking For Anything Specific?

[Tutorial ]Android Kotlin How To Pass Data Between Fragments

Hi Guys,

In this tutorial, I'm, going to write about how you can send data between one fragment to another in an easy and efficient way, by the end of this tutorial you will learn to pass data from fragment A to fragment B. If you wanted to learn how to pass data between activities read here: Android Kotlin Tutorial On How to Pass Data Between Activities So let's get started, before we get into the tutorial make sure you know all the basics like how to create a fragment in android studio, for that you can refer the below tutorial


So, now that you have learned how to create a fragment, you might as well create more than one in some occasion for your requirement in a way that they both are connected also you might want to send data from one fragment to another, and the good example for that type of scenario is product and details page, let's say you have a list of product and once you click on one product you might want to move to another page to show the details of the selected product, you can do it with Activities though but it is a good practice to use fragments in such scenarios as they both are under the same category.

Learn how to get activity result using ActivityResultAPI : [Tutorial] Get Android Activity Result in Kotlin With ActivityResult API

This tutorial is based on the above scenario only, but it can cover most of the things you need to know, so make sure you have already read us how to create a fragment with the kotlin tutorial. That rests the case now lest start sharing data between fragment. After Creating two fragments, Name it as ProductListFragment and ProductDetailFragment, also another Tip: Name the file with a suffix of their content like Fragment, Activity, or Adapter, so that you'll have an easy way to search and maintain the file. 

android pass data between fragments with kotlin


Open ProductListFragment and add the list of products of your choice, for now, I have chosen the day to day things from our kitchen, you know just being informative

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".ProductListFragment"
    android:gravity="center"
    android:orientation="vertical">

    <Button
        android:id="@+id/p1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/p1"
        android:layout_margin="16dp"/>
    <Button
        android:id="@+id/p2"
        android:layout_margin="16dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/p2" />
    <Button
        android:id="@+id/p3"
        android:layout_margin="16dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/p3" />
    <Button
        android:id="@+id/p4"
        android:layout_margin="16dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/p4" />
    <Button
        android:id="@+id/p5"
        android:layout_margin="16dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/p5" />

</LinearLayout>

Above is the code to add five buttons,  but I'm not gonna recommend doing this, it is for this quick tutorial because we can use recyclerview instead of this types of hardcoding five buttons, let's say you have a new requirement to add two more product then its a lot of work so Use recyclerview. Although my favorite is Constraint layout I have used LinearLayout here because its easy to do these kinds of view, so always know your requirement before choosing the layout of your choice, every layout has its own advantages. 

So After creating no. of buttons we can add some data that we want to pass on to the second fragment in our case it is the product detail page fragment. For this, I would recommend using the string resource file because it comes in handy if you want to translate your application. Add a bunch of strings or you can use one that's provided in the sample code of this post.

Now let's go from the basic, so what we have so far is two fragments one with buttons and the second fragment with a simple text view to show a Heading and Description of the selected button, more like a details page

How to switch between fragments in Android: 

This part actually I have covered in one of my previous tutorial where also I have shared the sample code, also to not get confused I'm using the same pattern here, with that I have also covered the basics of back stack handling when adding multiple fragments there 


How to pass data between two fragments:

Now in our hand, we have two fragments, A) ProductFragment B) ProductDetailsFragment, we want to share data from A to B, so A being the source and B being the destination, we start from our destination. What we are going to do is that we send the data to the fragment before calling the onCreate of the fragment.  So this is where the companion object comes in handy. You can learn more about companion objects here: Companion Objects in Kotlin. They help you to create Java equivalent static methods, those methods must be annotated with @JvmStatic. To create a static method in your destination fragment returning the instance of the same fragment itself like below

    companion object {
        @JvmStatic
        fun newInstance() =
            ProductDetailFragment()
    }

What the above method does is it will return a new instance of the ProductDetailFragment, In here we are going to pass the arguments that we required in the destination fragment from source fragment, In our case, it is heading and description, and once we supply those data as an argument to the function newInstance like this newInstance(heading: String, description: String) we might as well put those data into the fragments arguments, An argument to this fragment is a Bundle that is passed on to the fragment before it's been created, which is before the onCreate method and the data will stay still in the argument until onDestroy is begin called. So we will pass those data as Bundle into those fragments as arguments like below 

companion object {
        @JvmStatic
        fun newInstance(heading: String, description: String) =
            ProductDetailFragment().apply {
                arguments = Bundle().apply {
                    putString(HEADING, heading)
                    putString(DESCRIPTION, description)
                }
            }
    }

In the above code we used the apply scope function in kotlin to make the code a bit easier, so what it does is as mentioned above we are passing the data heading and description as Bundle to the fragments argument, Bundle is what we are using to pass data between fragment so the Bundle extends BaseBundle which has the function putString which accepts two parameters key and value, so the first one being the key and second is value. So now that we have passed the values to the fragment now we can instance it and pass the data. This Bundle allows you to send more than just string like you can send int, double, some examples were, putInt(key, value) and putDouble(key, value). Along with this, you can also send arrays for that you have to be more specific like IntArray, StringArray you can refer this android developers API reference for more details: Android Bundle

So we have five buttons, we need to set click listener onto every single one of them, (again Pro Tip: use RecyclerView. tutorial we will cover later)  you can use our previous tutorial on how to add a click listener to a button in android here. So once you have added the click listener to the fragment, we can now use the fragment transaction to move from source to destination 

  buttonMeat.setOnClickListener{
            val fm = fragmentManager
            fm!!.beginTransaction()
                .replace(R.id.fragmentContainer,
ProductDetailFragment.newInstance(getString(R.string.p1),getString(R.string.p1_details))
                    ,"ProductDetail").addToBackStack(null).commit()
        }

The above is the code to create an instance of the new fragment and pass data on to it, and the make the transaction. 

What we have done in the above code is that we create a click listener for a button, and the use fragmentManager to replace the fragment, in a normal transaction we just create an instance of the destination fragment, but we want to pass data, so to do that we create the instance with that fragments static method which allows as to supply two arguments. Pro Tip: We used an android string resource file to show the string.    override fun 

onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            headingText = it.getString(HEADING)
            descriptionText = it.getString(DESCRIPTION)
        }
    }


Note: The "HEADING" in the getString function is a string value. You can refer to the sample code for further details.

Well that we have passed our data to the fragments its time that we get the details in our Destination Fragment it's simple as it is like you just call the getArguments() method to get the value as arguments as kotlin getter property. we use let scope function for null safe values, and use the getString method inside and pass the key on to it to get the values you sent. 

send string to another fragment


After that you use a regular way to display the images on to a textview, actually, there is a great tutorial about that in here you can learn more than just setting the string to textview from fragment here, Above is the sample image where is the final output of the after setting those heading and description to their respective text views.

Learn how to share data between Activities Here


Congratulations!  now you can send data between two fragments easily, If you find this tutorial hard to read you can comment below on how it can be improved and as promised I'm sharing the complete project code on GitHub you can get it from below thank you for reading



final output:


PS: the output seems a little laggy due to emulator

In Case You Missed


!!!Spread the word!!!


keywords: