Hey Android Devs, thank you for reading this blog.
In this article, I am going to explain how to pass data between Fragments in the Navigation component.
This is 4th part of the series Navigation in Multipage apps.
If you are new to this series, please read those first to better understand Navigation.
Navigation in multipage apps | Part 1
Navigation in multipage apps | Part 2
Pass Data between Activities | Multipage apps
If you don’t have time, you just need the code, here is the GitHub repo,
Multipage Apps Sample
In the previous article, we discussed How to pass Data between Activities. Now we talk about passing data between Fragments.
What is the difference?
Is it possible to launch a Fragment using Intent?
How to provide type safety while sharing?
Wait for some time, I will answer these questions one by one.
As I said earlier, Activities are one of the App components. Android Framework will take care of handling data between Activities.
But Fragments are just a View or Mini Activity. So we will have to write the boilerplate code to handle everything.
Hey, we are in 2021, we have Jetpack Navigation Component.
With the Navigation component, we can share data easily with type safety.
You heard it right, with type safety. Even stable Bundle class didn’t provide this feature, but the Navigation component does.
Note: we can pass data without type safety, but I recommend using type safety as it provides a better Developer experience.
Let’s start.
- This is the navigation graph we created in the part 2
2. Click the fragment that receives the data. Here navSecondFragment is the target destination. And click Add Argument in the right panel.
3. Now add the configuration for SafeArgs, it provides TypeSafety for the Navigation Component.
4. Add the SafeArgs plugin in the project-level build.gradle file.
See Line no. 5 & 14
5. Apply the plugin in app-level build.gradle file.
See Line no. 4
6. Click sync now. It will generate some classes so that you can pass data with type safety.
7. In the NavFirstFragment.kt, in the click listener,
8. Add the action as below,
Note, we passed “Hello world” as data inside the method.
9. Then receive the data in NavSecondFragment.
// Add this variable in the NavSecondFragment class
private val args: NavSecondFragmentArgs by navArgs()
then you can access the data property as args.data
See Line no. 17 & 29
Now you know to pass data between Fragments.
Source: Navigation Component | Android Docs
Connect me on Twitter, LinkedIn.
Happy coding :)