Photo by Andrew Neel on Unsplash

navigateUp with Bundle!

Mahdi Nouri
AndroidPub
Published in
2 min readMay 11, 2019

--

It’s been a while that Google has released the Navigation component. It’s such a nice library for handling navigation in an Android application. But have you ever tried to navigate from a fragment to another to get a result from it? Google’s recommended way to achieve this is to use shared ViewModel, which means you have to deal with ViewModel boilerplate just for sharing data between fragments and beside that, in my opinion this is not an optimal solution just for sharing data between two Fragments specially when you are using single Activity pattern, because your ViewModels are going to stay in the memory for almost the entire life cycle of the application.

A better solution

I thought to my self why not handle this in just the way that startActivityForResult works. I mean you just have to override onActivityResult function and instead of starting your Activity with startActivity function, you would use startActivityForResult and pass a request code as second parameter and that’s it(at least for the starting point Activity).

Okay nice idea, but how?

I’ve worked on an open-source library to address this problem. I’ve tried to make this process as easy as startActivityForResult but for Fragments.

How to use

First of all we need to add NavigationResult’s dependency in our build.gradle file:

dependency {
implementation "com.phelat:navigationresult:1.0.0"
}

We need to extend our starting point fragment from BundleFragment:

By doing this we can access navigate function from BundleFragment which receives a second argument as request code:

And to receive the result from FragmentB we have to override onFragmentResult in FragmentA:

Now we can use navigateUp function which is an extension function on Fragment and receives a Bundle as second argument in our destination fragment to pass data from FragmentB to FragmentA:

Okay so now we are almost done but there is one more step to take, we have to extend our Activity from FragmentResultActivity.

We use FragmentResultActivity to store all the pending requests in it. You can also navigate with request code using FragmentResultActivities, same as you would do with BundleFragments.

Benefits

  • It’s 100% written in Kotlin
  • No shared view models results in less boilerplate

For sample code and more information about NavigationResult library please checkout the repository on GitHub.

--

--