英文:
Can I make a Fragment wait for data from Activity?
问题
我有两个活动,LoginActivity和HomeActivity,其中包含一个Tablayout和ViewPager 2。有三个片段(FragmentA,FragmentB,FragmentC),类似于HomeActivity中的选项卡。
登录后,我在HomeActivity中从Web服务器获取一些数据。这些数据是产品列表,我想在我的片段中使用。
我的问题是,在HomeActivity获取数据并填充列表之前,我的片段被创建,导致在片段中使用所述产品列表时出现空指针异常(NPE)。
有什么方法可以防止出现NPE?是否可以使片段等待,直到HomeActivity填充了产品列表?
当我在FragmentA内部使用按钮获取产品列表时,一切都按预期工作。但我希望在FragmentA的onCreateView中获取productList,这目前导致了NPE。
英文:
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.
答案1
得分: 0
可以借助以下解决方案来实现这一点:
- EventBus - 外部库 -> 可用于在数据获取成功时进行通知,然后您可以调用片段。
- LiveData -> 您可以为该网络服务编写一个观察者,每当观察者返回成功值时,您可以创建片段方法。
英文:
You can do this with the help of Solutions like :
- EventBus - External Library -> can used to notify when the data fetching is success and you can call the fragments after that.
- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论