0

I have created a quite nice implementation of a Broadcast/BroadcastReceiver where I am pulling down information via a Service from a Web API, Broadcasting the result of the received data and then changing the UI when the OnReceive function is called in the Activity which updates the UI.

The way I am updating the UI though is by passing the 'id' of the row to the database and then pulling the data out again.

This doesn't seem very optimal as I have to access the database twice. Once to save and once to retrieve. How can I optimise this? How can I optimise the process of updating the UI without having to go to the database again?

Options which I have researched:

  • Send a Parceable/Serializable object in the Intent when Broadcasting
  • Saving the retrieved data in a static class and using that data when onReceive is called.

Thank you in advance.

Subby
  • 5,370
  • 15
  • 70
  • 125
  • 1
    use a contentobserver on the cursor you open on the database. that way, you only need to react when you receive the notification that something was inserted in the database. That makes a good separation of data and view. – njzk2 May 05 '14 at 23:02
  • @njzk2 Is the ContentObserver only achieved through ContentProviders? – Subby May 06 '14 at 07:54
  • i am not sure, I think it also works without them too, as long as you use the same Uri for registering the notification and for publishing them – njzk2 May 06 '14 at 12:43
  • @njzk2 Do you know of any good tutorials? – Subby May 06 '14 at 12:48
  • this should be trivial enough. choose an Uri for your data (as if you were going to use it for a ContentProvider), then use `context.getContentResolver().notifyChange(uri, null);` when you modify a data, then use either `FLAG_AUTO_REQUERY` (discouraged) or `FLAG_REGISTER_CONTENT_OBSERVER` when you create the adapter and override the `onContentChanged` of the adapter to update the cursor yourself. Finally, call `setNotificationUri` on the cursor when you create it so it reacts to modifications. – njzk2 May 06 '14 at 13:02
  • I think i'd need a tutorial just to get me going. Though your explanation made some sense, I just need a slightly wider context as I'm still new to Android. Thank you btw for your very kind help. – Subby May 06 '14 at 13:13
  • I have written an article about saving stuff to database in a simple way: http://njzk2.wordpress.com/2013/07/09/storage-is-simple-part-1-sql/ It uses a contentprovider, but it is not mandatory to use it to retrieve data. The `notifyChange` and `setNotificationUri` are included, you only need to handle the `onContentChanged` in the adapter. (sorry I don't know any tutorial specifically about this point. I may write one at some point, though) – njzk2 May 06 '14 at 13:29

0 Answers0