我在Fragment类中有一个RecyclerView,还有一个Service类,我想在其中添加Item到我的RecyclerView中.问题是我对如何做到这一点一无所知.所以我问,有人告诉我要使用Otto.现在我有库存,因为它没有用.我的代码可能有问题,我不知道,这是我第一次使用Otto.
这就是我实现片段类的方式
public static class MyFragment extends Fragment {
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
static TheRecyclerAdapter theRecyclerAdpater;
private List theDataList;
public static Bus bus = new Bus(ThreadEnforcer.MAIN);
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.online_devices, container, false);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
linearLayoutManager = new LinearLayoutManager(getActivity().getBaseContext());
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setHasFixedSize(true);
theDataList = new ArrayList<>();
theRecyclerAdpater = new TheRecyclerAdapter(getActivity().getBaseContext(), theDataList);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(theRecyclerAdpater);
bus.register(this); //I already register my fragment
getActivity().startService(new Intent(getActivity(),MyService.class)); //I call the Service
return view;
}
//I already Subscribe, I am expecting to execute this Function but nothings happened
@Subscribe
public void getMessage(String s) {
TheData a = new TheData(s);
theDataList.add(a);
theRecyclerAdpater.notifyDataSetChanged();
}
}
这是我的服务班级
public class ServerHelperService extends Service {
public static Bus bus = new Bus(ThreadEnforcer.MAIN);
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate(){
bus.post("a"); //This where I'm expecting to call the getMessage function in my fragment
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
有谁知道为什么它不起作用?