2

I have an AsyncTask that fetches information from a web service and displays in the UI. This requires me to fetch the info every time the application starts, which wastes bandwidth and takes long for info to appear when you start the app.

I would like to store the fetched information in a local SQLite Database, and sync it every once in a while with the data from the web service.

What would be the best approach to do that?

If I create another AsyncTask for the database, and run it as soon as the app starts, I risk having a race condition where the database is updated as I'm reading information from it to display in the UI. What is recommended for this? I assume it's a common problem, though I wasn't able to find the right keywords to find an answer...

Thanks

Edit: My min API level is 8, so any solution should work with it or available in the support library.

tbkn23
  • 5,205
  • 8
  • 26
  • 46

2 Answers2

2

If you would like to cache your data locally in a SQLite database, consider creating a Content Provider which provides a wrapper around the SQLite database and also allows you to use Loaders which can pull information from your database and automatically update your UI as the underlying data changes.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
  • Thanks, I'll read about it and see. I noticed the loaders are for newer API levels only, and my min API level is 8. So how do I sync the GUI with the DB in the older API levels? – tbkn23 May 01 '13 at 20:01
  • @tbkn - Loaders are also in the Support Library and available back to API level 4: http://developer.android.com/tools/extras/support-library.html – ianhanniballake May 01 '13 at 21:46
0

I discouraged you to use AsyncTask to perform any network calls. As you mentionned it the AsyncTask is created again when the Activity is started again, including when you simply change the orientation of your device. Loaders are better but they have not been created to perform request calls since althought the loader is not created again when your activity is resumed the loader will be resumed but will restart its stuff from scratch.

The best approach is to use the Service API as mentionned in GoogleIO 2010. Since you want to perform some data persistency with local database from remote server I suggest you to use RESTDroid

Pierre Criulanscy
  • 8,726
  • 3
  • 24
  • 38
  • Yes, the AsyncTask was the temporary solution I used, I do not intend to keep using it (perhaps only for manual sync upon request). I posted another question, a bit different after additional research. See if you can help out there: http://stackoverflow.com/questions/16433709/syncing-a-rest-service-with-an-android-app?noredirect=1#comment23570228_16433709 – tbkn23 May 08 '13 at 08:00