0

I am making an app which gets a time schedule from a website and display it in my app in a nice ListView. To make the schedule available when the user is offline I am trying to save it in a SQLite database first and get the data from there. The idea is that the database gets updated when the user starts the app, when the user presses a refresh button and at set times by a service running in the background.

My question is: how can I efficiently update and get data from the database without using the UI thread, thus not blocking user interaction.

I think I should use a system which puts tasks in a queue so that the database gets updated before the data gets displayed in my ListView. Other than this I don't have a single clue how to realise such a system on Android.

Obe
  • 13
  • 5
  • Check out the [AsyncTask](http://developer.android.com/reference/android/os/AsyncTask.html) class. – nhaarman Feb 26 '15 at 12:10
  • I did. But AsyncTask only works when you start it from the UI thread. If I want to start it from my service it probably won't work? – Obe Feb 26 '15 at 12:13
  • why would you need to start an AsyncTask on a service? Your service is already seperate from the activity (and ui thread) – Evripidis Drakos Feb 26 '15 at 12:20
  • @EvripidisDrakos Hmm. Because I want also want to update the data from my service to push nice notifications when something in the schedule changes. An ideal solution would be some sort of task that can run from an activity and a service. – Obe Feb 26 '15 at 12:32
  • ok so, on the service do the same thing, but dont use an AsyncTask. On the app, use an AsyncTask. Dont know your code but I would create a function that take a db connection and whatever else is needed and updates the db from the net, and call that from either the service or the asynctask – Evripidis Drakos Feb 26 '15 at 12:35

1 Answers1

1

Ok so you need to implement three things:

1) Get data from website to db: for this you should use an AsyncTask

2) Make a ListView that will get data from the db and update automatically. For this you will need to use a Loader which will handle the loading of the data on the background.

3) To use the loader you will need a ContentProvider to provide you with the cursor needed and notify the ListView on changes.

For all three there are many nice tutorials online, for example see here

Evripidis Drakos
  • 872
  • 1
  • 7
  • 15
  • I didn't know there was something like Loader. Thank you for that. How should I update the data from my service? – Obe Feb 26 '15 at 12:33
  • the service will just update the content provider/database and optionally create a notification. The ListView will be linked with the contentProvider, so when the provider updates the db, it will also call notifyDataChanged which will prompt the ListView to update its data automatically. Its all in the link I posted – Evripidis Drakos Feb 26 '15 at 12:38