0

I have a view pager that is a fragment. Inside this, I have three fragments each one show a list of items that have the same model but filtered by one state (property in my model), for example like whatsapp that I have one list for all my conversations, other for conversations that I haven't read and finally other for that I've read.

The problem is that I have to refresh all the data when I'm inside the first fragment (all my conversations). So, I've tried to get all my data in the container fragment(view pager) but I cant see my first list with data(all my conversations) because when the container view is created, the first and second fragments is created too.

How can I get the data in the container (view pager) and immediately show the respective list in each child fragment?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38

1 Answers1

0

The solution is not to store data in any Fragment.

It is a very common use case that if a data is needed in Fragment (or Activity) X, then it will also be needed in Fragment Y. Sharing any state between Fragments is not easy and error prone, therefore I always advice to keep application's data in "application global scope".

What you need is some object, let's call it DataRepository, that lives in the scope of Application object and is injected into all Fragments. Since it lives in Application scope, the data is not tied to any specific Fragment and all Fragments can access and filter the data however you find appropriate.

The most convenient way to define such a "global" object is to use dependency injection framework (e.g. Dagger) and designate DataRepository as scoped injection in ApplicationComponent.

Vasiliy
  • 16,221
  • 11
  • 71
  • 127
  • Thanks! I understand :D But what happen if i would like to refresh the data every time I im inside that container and is visible the first fragment... where i have to supposed to make the call to the api ? I dont know if im clear :S – Raul Astete Oct 23 '17 at 20:49