Reputation: 14409
I have service that updates a database on my android APP. The thing is that the views on the APP itself (listviews) won't get notified if I don't explicitly call the "myAdapter.notifyDataChanged()" method. How can I do this from a service? Where I have no reference to the adapter nor the activity holding it.
I thought of firing my own custom event, but I don't know if that's even possible in android. I couldn't find anything on the API documentation.
Thanks in advance!.
Upvotes: 1
Views: 228
Reputation: 8170
The elegant way is having your activity bind to the service using bindService
. In this call you need to provide a custom ServiceConnection object which has a callback function called onServiceConnected
, where you can get a pointer to your service.
Once you have a pointer to your Service object, you can ask your Service to inform you (providing a pointer, a callback, a handler, or any other mechanism) to update the view when the database is updated.
Through this mechanism when your activity starts, it connects to the service, and when the activity ends (onPause()) you disconnect from the service.
It's not trivial, specially if you have never done this before, but this mechanism will be very useful for any kind of service.
Upvotes: 0
Reputation: 1006819
Use a message bus (LocalBroadcastManager
, greenrobot's EventBus, Square's Otto, etc.).
Or, use a Messenger
.
Or, wrap your database in a ContentProvider
and use a CursorLoader
to populate the adapter, as you will be handed a new Cursor
when you change the content in that ContentProvider
(assuming you implement it correctly).
Upvotes: 3