Data Transfer Between Fragment and BottomSheetDialogFragment Using Dagger and Navigation Component

Denis
2 min readAug 15, 2024

--

Data transfer between a Fragment and a BottomSheetDialogFragment can be effectively managed using Dagger and the Navigation Component, avoiding the use of data transfer through constructors or interfaces, as well as SharedViewModel and Hilt. This approach allows for a focus on dependency injection and state management through standard tools.

In our example, the key component is DaggerBottomSheetDialogFragment, which provides dependency injection and state management, offering flexibility and control over the process.

Using Dagger in this context allows for dependency injection, which opens up possibilities for extending functionality. When dependencies need to be injected into BottomSheetDialogFragment and other components of the application, Dagger helps maintain architectural cleanliness and flexibility.

Data Transfer

Data transfer between FirstFragment and SecondBottomSheetFragment is organized with a focus on bidirectional data flow as follows:

  • Sending Data: FirstFragment sends data to SecondBottomSheetFragment using the openBottomFragment method. In this method, arguments are set, and findNavController() is used for navigation.
  • Receiving Data: Values obtained from SecondBottomSheetFragment are observed in observeBackStack, where currentBackStackEntryFlow is used to track changes in the navigation stack state, followed by updating data in the ViewModel.

Let’s look at how this is implemented in code:

Note that in this example, the openBottomFragment method uses a check before performing a navigation action. This is necessary because rapid opening or closing of windows may result in an error related to the incorrect state of navigation. This error manifests as java.lang.IllegalArgumentException if the NavControllerattempts to perform navigation when the current fragment location does not support the transition.

Next, let’s consider the example in SecondBottomSheetFragment, where data from FirstFragment is received via initArgs, which initializes the ViewModel. The processed data is then sent back to FirstFragment through the sendDataToParentFragment method. This method allows for updating the user interface in FirstFragment, ensuring it reflects the changes made in SecondBottomSheetFragment.

This example demonstrates how to use Dagger and the Navigation Component for managing state and transferring data between fragments and a BottomSheetDialogFragment. The complete code is available at the GitHub link.

--

--