1

To me is diffucult to understand which the right workflow is to download json data and show them in a ListView. Currently i am using an AsyncTask to download and parse data that is shown using an ArrayAdapter. The problem is that AsyncTask doesn't survive to activity restarts.

So I am wondering if services are a better solutionbut how to pass data to the ArrayAdapter? Should I always use the db as middle layer to store and retrieve data?

So which is better? AsyncTask in retained fragment or service using db?

Thanks

Matroska
  • 6,885
  • 14
  • 63
  • 99
  • I personally found Fedor's Lazy Load method very flexible to work with. In fact, I use it even when there are no images to display in the list. http://stackoverflow.com/a/3068012/450534 – Siddharth Lele May 23 '12 at 11:22

3 Answers3

2

I use a service to do http data retrieval and storage into sqlite db. Once the service has stored the data (or if there is a problem) I then fire a broadcast. My Fragments / Activities listen for these defined broadcasts and then act appropriately.

I find that this is a very clean solution and avoids the problems of leaking asynctask references on activity teardown / rotation etc.

Damian
  • 8,062
  • 4
  • 42
  • 43
0

The most simple solution would be to return your current AsyncTask in onRetainNonConfigurationInstance or use a Fragment with setRetainInstance(true).

You can access the AsyncTask in inCreate with getLastNonConfigurationInstance

Renard
  • 6,909
  • 2
  • 27
  • 23
0

It actually depends on the requirement of what exactly the Activity needs and how long can the data be displayed without hitting the service again.

One approach to the above mentioned problem is, hit the service get the json data and store it in database. Now fetch the data from database and display it in the Activity. You can now implement a service to refresh the data when required. The service will simply hit the web service and update your db content as and when required.

cutebug
  • 475
  • 4
  • 10
  • It is a one shot...retrieve the data and display..using db seems a waste of time. I mean delete rows, insert rows and fetch them – Matroska May 23 '12 at 11:25
  • If that is the scenario you can bundle the json in assets. You can also have a mechanism to refresh the json content using a Service which talks to web service and store it as a file in internal memory. So you have a fallback mechanism, in case of data being updated in web server. Hope it helps. – cutebug May 23 '12 at 11:34
  • Btw you suggest the service approach over the asynctask one? – Matroska May 23 '12 at 11:39
  • Bundle the json with assets. Fetch the json using asynctask. Fetch the json from web service after some time probably a day or a week using Service and store it in internal memory. My suggestion here is fetching the json and updating the UI can still go with AsyncTask, but downloading the json from web service for future purpose should go in Service. – cutebug May 23 '12 at 11:43