-1

I am trying to know how many ways are there to pass the data between two fragments let's say from an Edit Text in one Fragment to a Text View in other Fragment.

I know two ways:

  1. First one is using the intent.
  2. Second is using the arguments in navigation.

Are there more ways to send data between two fragments and which one is more better and efficient and why ?

If anybody has any knowledge about this please tell.

oyeraghib
  • 878
  • 3
  • 8
  • 26
  • Intents are for activities. Fragments don't use Intents at all; there's really just the one way. – ianhanniballake Sep 17 '21 at 21:40
  • You can use some storage like database or shared preferences: save data in the first fragment and load it in the second fragment – Anatolii Chub Sep 17 '21 at 21:57
  • 2
    You can use a shared ``ViewModel`` to store data that the other Fragment can access. It's not so much "passing data" as putting it in a place where it can be retrieved (or if you're using the observer pattern, say with a ``LiveData``, if both fragments are active the one with the observer will see the update happening). If you need to persist the state (like would happen with Navigation) you can use a ``SavedStateHandle``: https://developer.android.com/topic/libraries/architecture/viewmodel-savedstate – cactustictacs Sep 17 '21 at 21:58
  • https://developer.android.com/guide/fragments/communicate – IR42 Sep 17 '21 at 22:09

1 Answers1

2

From my personal experience I think there are 6 ways:

  1. Navigation arguments
  2. Store state in parent activity and get it through callbacks or getActivity.
  3. Use some local storage like shared preferences or room.
  4. Store app state on a singleton and access it from the different fragments.
  5. ( The best one in my opinion without over engineering ) Have a shared view model between the fragments
  6. ( Not recommended because can cause crashes easily ) pass argument through the constructor of the second fragment
Sergio Pardo
  • 774
  • 6
  • 17