0

I wanted to know what are ways to send data from activity to fragment and what will be the best way to send.

I am aware of the fact that we can send data via bundle and setting data in the constructor. If so what are efficient ways to do so?

I felt bundle is an efficient way because you can send multiple data but while on rotation when your fragment is recreated then you can always get data by getArguments() while when you send data via the constructor of fragment it will not initialized again. Please tell me if my understanding is right?

samsap
  • 60
  • 2
  • 7
  • Possible duplicate of [Send data from activity to fragment in Android](https://stackoverflow.com/questions/12739909/send-data-from-activity-to-fragment-in-android) – Ali Ahsan Aug 09 '19 at 19:26
  • Use bundles for most part. The constructor method is not advisable as whenever the fragment will be restored by the framework (just like the case of rotation which you have identified) you will loose the values. If you want to send large volume of data or have greater means of communication use ViewModel / Database, etc – Arka Prava Basu Aug 09 '19 at 20:14

1 Answers1

3

Viewmodel comes to rescue in these situation. Viewmodel's one of the purpose is to survive configuration changes and in activity you can set your data into viewmodel and can access it in the fragment. Refer this https://developer.android.com/topic/libraries/architecture/viewmodel#sharing . Hope this helps.

  • Yes, I guess using custom Viewmodel class with Livedata can solve my problem efficiently of sharing data from fragment to activity. Thanks!! – samsap Aug 09 '19 at 22:28