java fragment_java-在Fragment和Service类中使用Otto

我在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();

}

}

有谁知道为什么它不起作用?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值