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();
}
}
解决方法:
您不能从其他“活动/片段”中调用片段的方法.
您有几种解决此问题的方法
计划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更简单!
标签:android-tablayout,android-fragments,android-viewpager,java,android 来源: https://codeday.me/bug/20191211/2105739.html