有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在初始化后向fragment发送数据

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

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

错误为next=>

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();
        }

    }

共 (1) 个答案

  1. # 1 楼答案

    不能从其他活动/片段调用fragment方法

    你有几种解决这个问题的方法

    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计划

    使用接口设计进行片段中的回调。必须为片段中的changingDataListenerimplements等更改数据创建一个接口,并从活动调用回调

    计划C(高级)

    使用PublishSubject可以为新数据创建可观察的,当新数据到达时,可以更新适配器

    相信我A计划要简单得多