- Android pass data between fragments
- Passing Data between Android Fragments using ViewModel
- Table of Contents
- Passing Data between Fragments by Defining Interface
- Passing Data between Fragments using ViewModel
- Example
- Setup
- Activity Layout
- Activity
- List Fragment
- List Fragment Layout
- Details Fragment
- Details Fragment Layout
- ViewModel
- Repository
- Model
- About
- How to Pass Data Between Fragments in Android using Kotlin
- Creating Fragments
- Passing Data Between Fragments
- Android Passing Data Between Fragments
- Android Tutorial
- Android Passing Data between Fragments
- Android Passing Data between Fragments Project Structure
- The modern way to pass data between fragments
- Pass data through Fragment Manager
- The modern way
- How it works
- Points to keep in mind
- Passing Data Between Fragments
- How to communicate between Fragments
- Four ways to communication between Fragments
- 1. Interface
- 2. ViewModel
- 3. RxJava
- 4. Event Bus
Android pass data between fragments
Passing Data between Android Fragments using ViewModel
If your application uses fragments, one fragment shows list of items and another fragment displays details of the selected item, then list fragment needs to pass the selected item id to the item-details fragment so that it can fetch data for the item and display in UI.
This post shows with an example how to pass data between fragments using ViewModel and LiveData.
Table of Contents
Passing Data between Fragments by Defining Interface
The most common way to pass data between the fragments is by defining an interface with a method which is implemented by the container activity of list and item details fragments. The list fragment calls the method implemented by the activity and passes the data (item id) to it. The method in the activity finds the item-details fragment and sets the data received from item fragment by calling a setter method defined in the details fragment.
Passing Data between Fragments using ViewModel
You can simplify and provide best solution using ViewModel and LiveData for passing data between two fragments of an activity. ViewModel has other advantages too such as separation of controllers from data handling and avoiding repeated data fetching due to configuration changes like screen rotation as view model is tied to activity lifecycle, for more information on view model see viewmodel tutorial.
To make passage of data from one fragment to another possible, we need to obtain view model object with activity scope in both fragments. Both fragments get the same view model instance which is tied to activity lifecycle. Item fragment passes item id to the set method of view model which sets the value on LiveData object. Details fragment listens to the live data object defined in the view model and capture the item id, fetches item details and displays it in UI.
Example
I’ll show how to implement communication between fragment using ViewModle and LiveData by taking players example. One fragment displays list of players in listview and second fragment shows details of the clicked player. On clicking a player in the list, live data object is updated with the selected player name. The second fragment which listens to live data for changes gets the selected player name and fetches and displays details in UI.
Setup
Add live data and view model dependency to build.gradle file.
Since we are using ToolBar, update styles.xml and use no action bar theme.
Activity Layout
Main activity layout contains two fragments.
Activity
List Fragment
List fragment gets an instance of view model using ViewModelProviders passing activity, fetches list of players and displays them in the list view. On-item-click listener calls a methods on view model to pass the selected player name to live data.
List Fragment Layout
List fragment layout contains list view which displays list of players.
Details Fragment
Details fragment gets the same view model instance which is used by the list fragment and adds change listener to live data object contained in it. The handler gets the selected player name, fetches the player details and displays in UI.
Details Fragment Layout
Detail fragment layout contains text views used for showing player details.
ViewModel
View model contains live data object, method to set value on live data object and methods which provide player list and details.
Repository
You can replace this repository class with something that fetches data from local db or remote source.
Model
About
Android app development tutorials and web app development tutorials with programming examples and code samples.
Источник
How to Pass Data Between Fragments in Android using Kotlin
UPDATE [April 17th, 2021]: Switched from Kotlinx synthetic to View Binding. If you haven’t implement View Binding in your project yet, check this tutorial.
Passing data from a Fragment to another Fragment it’s not the same as passing data from one Activity to another. You need first to pass the data to Activity and then to the second Fragment.
If you have created your fragments and you just want to know how to pass data from one Fragment to another, skip the following step.
Creating Fragments
In this example, we have a fragment that contains an EditText, where we type a text and a Button that sends the text to the 2nd fragment and shows it in a TextView.
First, let’s go and create the layout of the fragment with the EditText and the Button (fragment_1.xml)
Next, let’s do the same for the fragment with the TextView (fragment_2.xml)
Go and add an id with a name ‘content_id’ on parent layout in the activity_main.xml file like the image below:
Now, let’s create the Kotlin class for our first fragment (Fragment1.kt) and second fragment (Fragment2.kt) like that:
Passing Data Between Fragments
When we want to pass data between fragments, we are doing it with the help of the Activity which contains these fragments.
In our example, the Activity is the MainActivity.kt.
So we are going to use the MainActivity to pass the data from the first to the second fragment using an interface.
In our example we call it Communicator:
Inside the interface there’s a method passDataCom where we pass the input text from the EditText from our first fragment.
Now, add Communicator at the top of the MainActivity and implement the methods by pressing Alt+Enter(Windows) or Command+Enter(MacOS), then Enter and OK on the new window.
Next, let’s go to Fragment1.kt and initialize our Communicator and call the method with the text from the EditText as a parameter:
Now it’s time to go back to our MainActivity and pass the value from Fragment1 to the Fragment2.
To do that, we’re taking the value and we’re adding it to a Bundle.
Then we pass the bundle data as arguments to the Fragment2
And at the end we display the new fragment by replacing the Fragment1 with the Fragment2 in the MainActivity like that:
In the code above, we gave a key name “input_txt” for our text. This will help us to retrieve the value from our 2nd fragment.
After we have sent the value from the 1st fragment, it’s time to retrieve it from our 2nd fragment and display it on the screen.
Go to our Fragment2 and paste the following code:
Here we’re getting the value with the key name, we put earlier, and we display it on a TextView.
If you have any questions, please feel free to leave a comment below
Источник
Android Passing Data Between Fragments
Android Tutorial
In this tutorial, we’ll be developing an application that contains TabLayout, ViewPager and Fragments. We’ll implement a functionality that passes data from one Fragment to the other fragment.
Android Passing Data between Fragments
Intents are only usable for sending data on an Activity level. To pass data between fragments we need to create our own interfaces. The flow to send a String data from one Fragment to another is shown below.
Let’s get started with the implementation of the above flow.
Android Passing Data between Fragments Project Structure
The xml layout for the MainActivity.java class is given below.
The styles for the TabLayout and ToolBar are defined in the styles.xml file as shown below.
The ViewPagerAdapter.java is where the Fragments are initialised. The code is given below.
FragmentOne would be sending the data entered in EditText to FragmentTwo.
The xml layout for fragment_one.xml is given below.
The xml layout for fragment_two.xml is given below.
The code for FragmentOne.java class is given below.
The Custom Interface namely SendMessage is initialised in the onAttach method above. This interface would be implemented in the MainActivity.java that we’ll be seeing shortly.
The code for FragmentTwo.java class is given below.
The displayReceivedData() would be called on the instance of FragmentTwo.java from inside the Custom Interface’s method inside the MainActivity.java as shown below.
The sendData() method in the above code gets triggered as soon as the Button in FragmentOne is pressed. We fetch the FragmentTwo that was already initialised in ViewPagerAdapter using the method findFragmentByTag.
The output of the above application in action is given below.
This brings an end to this tutorial. You can download the final Android PassingDataBetweenFragments Project from the link below.
Источник
The modern way to pass data between fragments
Pass data through Fragment Manager
With Android Jetpack components a lot of things are happening here and there. Nowadays most of the developers tend to use Single Activity architecture, with that communicating between fragments become more crucial.
There are multiple ways to communicate between fragments. For example, using Interfaces or a shared ViewModel. But, this is sometimes additional overhead. As an alternative setTargetFragment could be used but, this is also now deprecated.
So, let’s look at the modern way.
The modern way
Beginning from Fragment release 1.3.0-alpha04 and onwards FragmentManager can be used to communicate between fragments. Now FragmentManager by default implements from FragmentResultOwner and override the methods to set and clear fragment results and fragment result listeners.
How it works
The FragmentManager holds fragment results and fragment result listeners in separate Maps with requestKey as a unique identifier. The fragment result listener which registered to the relevant requestKey get notified when the result is set or updated.
This way it helps to communicate between fragments in the same FragmentManager and also child to parent fragment or vice versa.
To pass data between fragments in the same fragment manager, the listener should be added to the destination fragment with requestKey in order to receive the result produces from another fragment with the same key.
Now, the source fragment should produce the result on the same FragmentManager with the same requestKey as follows:
That’s it, the destination fragment will receive the result and execute listener callback once it’s STARTED.
To pass data from child to parent fragment, should follow the same way by using childFragmentManager instead parentFragmentManager when set result listener to the parent fragment.
Now, same as the previous example, child fragment should produce the result with the same requestKey.
Yes, all you need. The parent fragment will receive the result immediately. If communication requires to be done other way around (pass data from parent to child fragment), the result listener should be set to child fragment and result should be produced from parent fragment. Then don’t forget to use childFragmentManager instead parentFragmentManager when producing the result from the parent fragment.
Points to keep in mind
- Only a single listener and result can be registered to the given key. If more than one listener is registered for the same key, it will be replaced for the latest one.
- If destination fragment in back stack, and calls setFragmentResult() from source fragment more than once for the same key, the system sends the most recent result to the destination fragment before the source fragment is popped off the back stack.
- If the result is set without having listener to receive it, the result is stored in the FragmentManager until the listener is set with the same key. When the listener is set and the fragment is STARTED, it will receive the result immediately.
- The result will be cleared from FragmentManager once the destination fragment receives it.
The example project can be seen here and more info here .
Hope you learn something useful. See you in the next one ✌️
Источник
Passing Data Between Fragments
In this post, we’ll learn how to pass data between fragments in Android. I will also explain, what is possible ways of communicating between two fragments in Android. There’s always need for communication between fragment.
How to communicate between Fragments
You guys well know Fragment is a reuse UI component, It should be built self-contained, modular that defines its own layout and behavior. Once you have written these reusable Fragments, you can associate them with an Activity.
Normally, two Fragments should never communicate directly. There’s always need for communication between Fragments, and this is a very common requirement in the real project, for example, to change the content based on a user event. etc.
Four ways to communication between Fragments
Android has several ways to do that. In this tutorial, I will tell all the possible ways. If you have any feedback or improvement suggestions are more than welcome.
- Interface
- ViewModel
- RxJava
- Event Bus
You can add here If I have missed. These are the best ways for communicating between one fragment to another fragment. In this article, I will explain only using Interface. For other ways, I will write a separate article.
1. Interface
The interface is the simplest way to communicating between two fragments in android. In this approach, we can define an interface in the Fragment class and implement it in Activity. whoever conforms to that interface, can be informed by the Fragment of events. Basically, Fragment capture the interface implementation onAttach() lifecycle method. Somethings like that
Attached with Activity
I have written a separate article on Fragment communication using Interface that gives more insight into this.
2. ViewModel
ViewModel is a recommended way by Google to communicate between fragments. In this approach, we create a shared ViewModel object. Both fragments can access the ViewModel instance and this instance(ViewModel) is associate fragments containing Activity.
I have written a separate article on this approach the below post gives more insight into this.
3. RxJava
This way is pretty good and easy to implement. Personally, I feel this is the best way to communicating two fragments in Android. In this technique, We use PublishSubject to create our own RxBus. This PublishSubject emits all the subsequent items of the source Observable.
4. Event Bus
EventBus is a publish or subscribe event bus for Android and Java. It simplifies communication between components. Personally, I don’t like this technique because It very loosely coupled and every broadcast can listen to events from a singleton instance. When the project very scalable then makes it very hard to maintain.
Источник