1

Although I have not tried it yet, but from theoretical point of view I'm asking this question just to clear my doubts.

I have a scenario like: 1. Send a request to a server and receive JSON response. For this I'm using AsyncTask as there can be delay in receiving response. 2. From this response fetch an image URL. 3. Using one more AsyncTask, call the image URL and fetch the image. (Again may take time to fetch image)

So do you think using of 2 AyncTask just to get that image is inefficient. OR, in step 1, instead of using AsyncTask, run the code sequentially and set Timeout instead.

Please suggest.

reiley
  • 3,759
  • 12
  • 58
  • 114
  • 3
    I may be missing something, but is there any reason you can't fetch the image synchronously in the Asynctask's thread (doInBackground)? – dennisdrew Oct 10 '12 at 20:32
  • 3
    yeah, do it all in 1 asnyctask – james Oct 10 '12 at 20:33
  • 1
    and if images are in large number you can use [LazyLoading](http://stackoverflow.com/questions/541966/android-how-do-i-do-a-lazy-load-of-images-in-listview) – maninder singh Oct 10 '12 at 20:38

2 Answers2

1

I'm going to go ahead and suggest this as an answer, which was originally in my comment:

Just fetch the image synchronously in the same AsyncTask that you're fetching the JSON from. For example:

doInBackground(Void...params){
    //fetch JSON
    // once JSON is fetched, fetch image
}
dennisdrew
  • 4,399
  • 1
  • 25
  • 25
0

Not sure how you want to structure this exactly, but documentation says:

execute(Params...) must be invoked on the UI thread.

http://developer.android.com/reference/android/os/AsyncTask.html

so you cannot execute new async task from other async task background method.

even if you tried doing this from progress method, then since HONEYCOMB asynctasks are serialized, so your second async task will get queued anyway - you would have to use THREAD_POOL_EXECUTOR to make it run parallel.

aandis
  • 4,084
  • 4
  • 29
  • 40
marcinj
  • 48,511
  • 9
  • 79
  • 100
  • Couldn't he technically make the call in onPostExecute of the first task (if he chooses to continue with a 2 Asynctask method)? – dennisdrew Oct 10 '12 at 20:51
  • sure, but in my opinion one task should be more efficient and it would introduce less complexity. – marcinj Oct 10 '12 at 20:54
  • 1
    The way the question is worded, it sounds like he's asking if he can start it in AsyncTask's doInBackground(). He *can* call the new AsyncTask in onPostExecute if for some reason he wanted to keep the implementations of the two objects separate. That might be desirable if there were more than one ways to get an image URL in the app. Then he can reuse the second AsyncTask for any case. – DeeV Oct 10 '12 at 20:54