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

问题描述 投票:3回答:1

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

    }
java android android-fragments android-viewpager android-tablayout
1个回答
2
投票

你不能从其他Activity / 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在片段内抓取您的数据。将此功能添加到Fragment中

@Subscribe
public void onEvent(EventClass event) {
     oneAdapter.setData(event.getPopulatedList());
}

4不要忘记在Fragment中注册和取消注册EventBus

EventBus.getDefault().register(this);//add in onCreateView
//...
EventBus.getDefault().unregister(this);//add in onDestroyView

计划B.

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

计划C(高级)

使用带有PublishSubject的RxJava,您可以创建Observable来观察新数据,当新数据到达时,您可以更新适配器。

相信我的计划A更简单!

© www.soinside.com 2019 - 2024. All rights reserved.