Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了java-初始化后将数据发送到片段 大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

将数据发送到初始化选项卡时出现问题.在方法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();
        }

    }
@H_696_24@
最佳答案@H_696_24@
您不能从其他“活动/片段”中调用片段的方法.

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

计划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在片段中抓取数据.将此功能添加到片段

@Subscribe
public 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更简单!

@H_696_24@

大佬总结

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

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

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。