I have a RecyclerView inside a Fragment class, and I have a Service class where I wanted to add Item into my RecyclerView. The problem is I have no any idea on how can I possibly do that. So I've asked and someone told me to use Otto
. And now I'm stock because it's not working. Maybe there's something wrong with my code, i don't know, This is the first time I used Otto
.
This is how I implement My Fragment Class
public static class MyFragment extends Fragment {
RecyclerView recyclerView;
LinearLayoutManager linearLayoutManager;
static TheRecyclerAdapter theRecyclerAdpater;
private List<TheData> 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();
}
}
And this is My Service Class
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();
}
}
Does anyone has an idea why it's not working?