android loop inside asynctask or asynctask inside loop - android

I have list of items to be syncronized with cloud. Let's say it has 10 items, so I have to make 10 HTTP requests to server. The question is: which approach should I use and why?
foreach loop inside one async task
10 async tasks inside foreach loop?

Better would be to have one AsyncTask and loop in in. And here is why:
All AsyncTasks will by default on one background thread (with API 11+, eg Honeycomb), so your 10 tasks will still execute sequentially, but meanwhile will take much more memory. So it's really better to run only one AsyncTask and if you need - publishProgress on execution process.
Here is SO answer about having multiple AsyncTasks.
Another approach is passing Executor to your AsyncTask, so it can break the limit of simultaneously runned AsyncTasks. But still it can be really memory consuming.
Aslo you might want to read this Android Developers guide.

Related

Multiple AsyncTask vs multiple requests within one AsyncTask

I'm following this tutorial to create an XML reader with options to download multiple feeds at once. Are there any downsides to executing multiple AsyncTasks (max 3) simultaneously? I'm going to add a timer to check if they finished.
Running multiple AsyncTasks at the same time -- not possible? It is possible. However it could be, that due to the cpu depending on each device, one is faster than the other. But as #Alex already answered, you wont get "real" multitasking. Haven't it tried yet I would assume, that doing it all in one AsyncTask is faster. And you could reuse the connection you established to the server.
For better architecture I'll choose 1 AsyncTask per request. It is easier to manage actual request. Also it would be easier to modify (add/remove request).
Downsides of executing multiple AsyncTasks depend on your knowledge of AsyncTask lifecycle. You need to execute it correctly (depends on android version).
Good article about the dark side of Async tasks http://bon-app-etit.blogspot.com.by/2013/04/the-dark-side-of-asynctask.html
They won't be run simultaneously, but serially. See here:
When first introduced, AsyncTasks were executed serially on a single
background thread. Starting with DONUT, this was changed to a pool of
threads allowing multiple tasks to operate in parallel. Starting with
HONEYCOMB, tasks are executed on a single thread to avoid common
application errors caused by parallel execution.
If you truly want parallel execution, you can invoke
executeOnExecutor(java.util.concurrent.Executor, Object[]) with
THREAD_POOL_EXECUTOR

Can you have two AsyncTasks in one Activity?

I have already developed an Activity which will parse JSON data and display the results in a ListView. I am using an AsyncTask for this purpose.
What I want now is that, when I click on an item in the ListView, the file should start downloading. Can I write another AsyncTask in the same activity so that this AsyncTask will do the downloading work for me? Is there any problem with having multiple AsyncTasks in the same activity?
As per from the Doc yes you can.
When first introduced, AsyncTasks were executed serially on a single
background thread. Starting with DONUT, this was changed to a pool of
threads allowing multiple tasks to operate in parallel. Starting with
HONEYCOMB, tasks are executed on a single thread to avoid common
application errors caused by parallel execution.
If you truly want parallel execution, you can invoke
executeOnExecutor(java.util.concurrent.Executor, Object[]) with
THREAD_POOL_EXECUTOR.
BEst answer How is itself on stackoverflow.
There shouldn't be any problem with multiple Asynctasks in a single activity. You should be careful to clearly define the values that each one manipulates (for example, if task B relies on a value given by task A, make sure that A must finish first), but in general, it should be fine. I have a project right now with three asynctasks running upon first install, and it's ticking along fine thus far.
Yes.. You can.
AsyncTask is simple thread handler implementation.

How to modify UI's views in other thread different than the main one due to heavy modifications

I have the following problem. I'm working on a mobile solution that consumes data from a server. For thoses HTTP transactions I obviously use an AsyncTask in order to separate this communication task from the main thread. However, after a successful response I need to build a Really Big Table Layout (with 2000 - 10000 table rows or more) to insert all the records coming inside the data. So if I start to build the table in the main thread I'll always get a ANR problem (Application Not Responding Dialog).
On the other hand, it's widely known that I cannot modify/add/touch elements from a different thread that is not the UI thread, so I have not been able to do this heavy table processing.
Suggesstions are heard. Thanks in advance.
You can archive it with pagination, you can show 20 rows first, when you scroll down and reach the bottom, add the other block of 20 elements and so on.
Why not just use the onPostExecute method of your AsyncTask to accomplish this? You can do all of the heavy processing in doInBackground, and then when you are done, simply update the UI in onPostExecute, which runs on the UI Thread. You can find more information on AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html

Android: Future/FutureTask for parallel processing of data

I am trying to optimize a complex data updater and parser for my Android app. The server provides three interface functions. The parser requires the data from all those three functions.
When the download of the data is finished, the parser can start. It consists of many different independent tasks which can be parallelized.
I was thinking of using Futures or FutureTasks for processing the data.
So basically, this is the procedure:
create Task-1, Task-2, Task-3 for downloading the data
wait for the downloads to be finished
create Task-1,..., Task-N for parsing the data
wait for the parser to be finished
call a callback to signal that process is done.
My first question: is it possible to create Futures with asynchronous functions, which use callbacks to return the data (network framework)?
Second question: are there any drawbacks in using Futures or FutureTasks respectively in this scenario or are there any better solutions to achieve that?
Thank you.
Basically you are Trying to achieve the following.
Step 1 - User from UI starts 1,2,... n download tasks.
Step 2 - Once each of the task is completed, new thread should be started to process it.
Step 3 - Once all n Tasks are completed, UI should be updated ... may be with a success dialog.
This can be achieved easily by using Async Task. I am going to tell you the approach and not the code sample.
Things to note about Async Task
Before 1.6, Async Task handles all background operations with a single additional thread.
After 1.6 till 3.0 .. it was changed, so that a pool of thread had begun to be used. And operations could be processed simultaneously.
Since Honeycomb default behavior is switched back to use of a single worker thread (one by one processing).
How to implement your requirement
For your requirement, you can use the method (executeOnExecutor) to run simultaneous tasks (1 till n tasks) if you wish (there two different standard executors: SERIAL_EXECUTOR and THREAD_POOL_EXECUTOR).
The way how tasks are enqueued also depends on what executor you use. In case of a parallel one you are restricted with a limit of 10 (new LinkedBlockingQueue(10)). In case of a serial one you are not limited (new ArrayDeque()).
So the way your tasks are processed depends on how you run them and what SDK version you run them on. As for thread limits, we are not guaranteed with any, yet looking at the ICS source code we can say that number of threads in the pool can vary in range 5..128.
When you start too many tasks (like 100s or more) with default execute method serial executor is used. Since tasks that cannot be processed immediately are enqueued you get OutOfMemoryError (thousands of tasks are added to the array backed queue).
Exact number of tasks you can start at once depends on the memory class of the device you are running on and, again, on executor you use.
So by following this approach, once all the tasks are completed, you can use a handler to update the UI.
Hope this helps.

Which AsyncTask should I use behind SERIAL_EXECUTOR in Android

I am retrieving already created data in all user controls. And there are 3 Spinners so I am using SERIAL_EXECUTOR to execute it one by one. But now, issue is that, one Spinner retrieves data based on another Spinner.
So which AsyncTask executor should I use for that Spinner by which It can load its data although SERIAL_EXECUTOR is going on.
In short, I want to know which AsyncTask should I use which will execute that Task even though SERIAL_EXECUTOR is in process.
If you want to execute an AsyncTask parallel to another one then you can use THREAD_POOL_EXECUTOR like this:
AsyncTask task = new SomeAsyncTask();
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
But I warn you that this might not work as good as you might like. If the AsyncTasks you are executing perform quite a bit of work on their own than executing them in parallel will slow them down considerably. If possible, try to execute tasks serially, only execute in parallel if you absolutely have to. If you need to load data which is dependent on some other kind of data consider doing it in one big AsyncTask instead of splitting the work to to AsyncTasks. Always try to keep the amount of AsyncTasks or Threads to a minimum. The fewer you have the faster your app will load.

Categories

Resources