java-初始化后将数据发送到片段

java-初始化后将数据发送到片段,第1张

概述将数据发送到初始化选项卡时出现问题.在方法getData()中,我收到的适配器为null,recyclerview也为null.TabOne one = new TabOne() one.getData(populatedList) 错误是下一个=>java.lang.NullPointerException: Attempt to invoke virtu

将数据发送到初始化选项卡时出现问题.在方法getData()中,我收到的适配器为null,recyclervIEw也为null.

TabOne one = new TabOne()one.getData(populatedList)

错误是下一个=>

java.lang.NullPointerException: Attempt to invoke virtual method 'voID OneAdapter.setData(java.util.List)' on a null object reference.

最好是通过捆绑发送数据包中的片段或其他任何想法.

我叫getData(),因为这里是来自API的响应.

public class TabOne extends Fragment {        private Unbinder unbinder;        @BindVIEw(R.ID.fab)        floatingActionbutton floatingActionbutton;        @BindVIEw(R.ID.recycler_vIEw_recycler)        RecyclerVIEw recyclerVIEw;        private OneAdapter oneAdapter;        private List<Response> response = new ArrayList<>();        @Nullable        @OverrIDe        public VIEw onCreateVIEw(@NonNull LayoutInflater inflater,@Nullable VIEwGroup container,@Nullable Bundle savedInstanceState) {            VIEw vIEw = inflater.inflate(R.layout.tab_one,container,false);            unbinder = ButterKnife.bind(this,vIEw);            linearlayoutmanager linearlayoutmanager = new linearlayoutmanager(getContext());            oneAdapter = new OneAdapter(getContext(),response);            recyclerVIEw.setLayoutManager(linearlayoutmanager);            recyclerVIEw.setAdapter(oneAdapter);            return vIEw;        }        public voID getData(List<Response> response){            oneAdapter.setData(response);        }        @OverrIDe        public voID onDestroyVIEw() {            super.onDestroyVIEw();            unbinder.unbind();        }    }
最佳答案您不能从其他“活动/片段”中调用片段的方法.

您有几种解决此问题的方法

计划A(建议)

使用EventBus库

1:像这样创建EventClass.java

public class EventClass{    private List<FILL IT WITH YOUR OBJECT> populatedList;    public EventClass(int populatedList) {        this.populatedList= populatedList;    }    public int getPopulatedList() {        return populatedList;    }}

2:使用

在你的活动中而不是这个

TabOne one = new TabOne()one.getData(populatedList)

使用EventBus并像这样发布您的事件

EventBus.getDefault().poststicky(new EventClass(populatedList));

3在片段中抓取数据.将此功能添加到片段

@Subscribepublic voID onEvent(EventClass event) {     oneAdapter.setData(event.getPopulatedList());}

4不要忘记在Fragmet中注册和注销您的EventBus

EventBus.getDefault().register(this);//add in onCreateVIEw//...EventBus.getDefault().unregister(this);//add in onDestroyVIEw

计划B

将接口设计用于片段中的回调.您必须为诸如changeDataListener之类的更改数据创建一个接口,并在Fragment中实现该接口,并从Activity调用callBack

计划C(高级)

将RxJava与PublishSubject结合使用,可以创建Observable来观察新数据,并在新数据到达时可以更新适配器.

相信我,计划A更简单!

总结

以上是内存溢出为你收集整理的java-初始化后将数据发送到片段 全部内容,希望文章能够帮你解决java-初始化后将数据发送到片段 所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1145059.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存