可以让片段等待来自活动的数据吗?

huangapple go评论63阅读模式
英文:

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

可以借助以下解决方案来实现这一点:

  1. EventBus - 外部库 -> 可用于在数据获取成功时进行通知,然后您可以调用片段。
  2. LiveData -> 您可以为该网络服务编写一个观察者,每当观察者返回成功值时,您可以创建片段方法。
英文:

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.

huangapple
  • 本文由 发表于 2020年9月8日 23:39:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/63797237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定