In my Fragment
class, this is how I add an Item to my RecyclerView
.
@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);
TheData a = new TheData("01","another value","another value","another value","another value");
theDataList.add(a);
a = new TheData("02","another value","another value","another value","another value");
theDataList.add(a);
theRecyclerAdpater.notifyDataSetChanged();
return view;
}
But what if I want to add an Item to my RecyclerView
via Service
when the UI
is Available? I mean, The Service
is running in background and if the Main UI
of application where the RecyclerView
is Available
then Add an Item Otherwise don't Add an Item. Anyone has an idea on how can i possible do that?
For now, I only have this in my Service
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate(){
//Add an Item here to RecyclerView if the UI is Available.
}
@Override
public void onDestroy() {
super.onDestroy();
}
UPDATE I just try this but not working.
@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);
getActivity().startService(new Intent(getActivity(),MyService.class));
bus.register(this);
return view;
}
@Subscribe
public void getMessage(String s) {
TheData a = new TheData(s);
theDataList.add(a);
theRecyclerAdpater.notifyDataSetChanged();
}
in my Service
@Override
public void onCreate(){
bus.post("PP");
}