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 楼答案
不能从其他活动/片段调用fragment方法
你有几种解决这个问题的方法
A计划(建议)
使用EventBus库
1:像这样创建
EventClass.java
2:使用它
在你的活动中而不是这个
使用EventBus并像这样发布您的活动
3在片段中绘制数据。将此函数添加到片段中
4别忘了在Fragmet中注册和注销EventBus
B计划
使用接口设计进行片段中的回调。必须为片段中的
changingDataListener
和implements
等更改数据创建一个接口,并从活动调用回调计划C(高级)
使用
PublishSubject
可以为新数据创建可观察的,当新数据到达时,可以更新适配器相信我A计划要简单得多