Search code examples
javaandroidandroid-activityfragment

Can I make a Fragment wait for data from Activity?


I have 2 Activities, LoginActivity and HomeActivity, which has a Tablayout and ViewPager 2. There are 3 Fragments (FragmentA, FragmentB, FragmentC) resembling the tabs in HomeActivity.

After Login, I am fetching some data from webserver in my HomeActivity. The data is a list of products, that I want to use in my Fragments.

My Problem is that my Fragments are created BEFORE HomeActivity could fetch the data and populate the list, resulting in a NPE while using the said productList in my Fragments.

What can I do to prevent that NPE? Is it possible to make the Fragments wait until productList is populated by HomeActivity?

When I am using a button inside FragmentA to get productList, everything works as intended. But I would like to get productlist onCreateView of FragmentA instead, which results in NPE right now.


Solution

  • You can do this with the help of Solutions like :

    1. EventBus - External Library -> can used to notify when the data fetching is success and you can call the fragments after that.
    2. LiveData -> You can write an observer for that webservice and when ever the observer is returning the success value , you can create you fragments methods.