How to update the RecyclerView Dataset
from the background service.
The service maintains a socket connection with the server and when the server responds with data, the service
has to update that in the recyclerview (that is in the MainActivity).

- 1,629
- 2
- 21
- 43
-
be specific, show your attempts to solve the problem – injecteer Jul 21 '16 at 13:13
2 Answers
There is many way to send event from Serivce to Activity.
I recommend you the following way.
Bind and Callbacks
I think that Bind and Callbacks is official way.
Communication between Activity and Service
Example: Communication between Activity and Service using Messaging
EventBus
I think that EventBus is easy way.
https://github.com/greenrobot/EventBus
In Activity (or any where) :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
@Override
protected void onResume() {
super.onResume();
BusHolder.getInstnace().register(this);
}
@Override
protected void onPause() {
super.onPause();
BusHolder.getInstnace().unregister(this);
}
@Subscribe
public void onDatasetUpdated(DataSetUpdatedEvent event) {
//Update RecyclerView
}
}
BusHolder holds BusEvent instance:
public class BusHolder {
private static EventBus eventBus;
public static EventBus getInstnace() {
if (eventBus == null) {
eventBus = new EventBus();
}
return eventBus;
}
private BusHolder() {
}
}
The event posted:
public class DataSetUpdatedEvent {
//It is better to use database and share the key of record of database.
//But for simplicity, I share the dataset directly.
List<Data> dataset;
public DataSetUpdatedEvent(List<Data> dataset) {
this.dataset = dataset;
}
}
Send message from your Service.
BusHolder.getInstnace().post(new DataSetUpdatedEvent(dataset));
I hope this helps.
May be you should use some database like thing to store temporary data because I don't think it's a good thing to store data in an object on behalf of service component. It would be redundant to store whole list data into object as whether user comes back to app or not your object is going to cover memory which we should avoid throughout the development process. Best of luck.

- 673
- 2
- 9
- 27
-
-
The service also inserts the data in the sqlite server (of android) and updates in the recyclerview too. – shikhar bansal Jul 21 '16 at 18:49