So, I'm working on a barcode decoder, which once we have the barcode goes to multiples API over the internet to decode what was just scanned. The thing is that I have to link some XML parsing together, and I don't know if I'm doing it right.
So, once the barcode is scanned, my program calls an ASyncTask which goes over an API to retrieve the product name. Once it has the name, I want it to call another ASyncTask. I know this is possible by instantiating an ASyncTaks in the onPostExecute()
of the other but, I think this is wrong, because it's like boxes within boxes.
So isn't it possible/better to instantiate my second ASyncTask inside my main Activity, and make it wait until my first ASyncTask is finished ?
(english isn't my primary language, I hope I made myself clear).
The Async task by default runs the tasks in serial fashion, one after the other. Once the task is not complete, the other tasks are waiting in the Queue to be picked up. We can override this serial runner by passing in our Executor, which can run multiple tasks in Parallel.
In newer Android versions, 5 threads are create by default, and the ThreadPoolExecutor will attempt to run the AsyncTask s on these 5 threads. If you create more than 5 AsyncTask s, it may either queue them or create new threads (but only up to 128).
It is possible but it will crash if you try to modify the UI from the onPostExecute on the second task as it is not executing in the main thread. IF your second task not contains UI operation, you can start. Its advisable to start async in post execute of first async.
An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .
I think it's absolutely legitimate to start the second AsyncTask
in the onPostExecute
of the first AsyncTask, Mixing both operations is a bad logical idea, As "The Offspring" said - "You've gotta keep 'em separated"
If you don't want it to be directly inside the onPostExecute
itself, set a handler to execute it in the activity and call this handler from onPostExecute
.
And last thing - If you have a lot of logic - move it to a separate file, don't keep it all at the same file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With