I have the next simple question. I have an AsyncTask that connects my client to a server. For each task the server does I need another one AsyncTask class?
Let's say that I need a task to fill an array from the server, another to return an integer from the server and one to return an object from the server to the client, I need 3 AsyncTask classes, one for each of these tasks?
AsyncTask is good when you don't need to present any information to your user. Something like saving data to the server, that nobody really cares when it finishes.
When you need something to be loaded for the screen, you'd be better off with AsyncTaskLoader class, that provides all the necessary callbacks.
Besides that, I'd create as many AsyncTasks as necessary. They are cheap, they make the work done. Why worry?
Here is what you can do
1) you can call your 1 st async task from class A and add an interface to that asynctask which has one method like onfirstTaskCompleted()
2) call onfirstTaskCompleted() method in onPostExecute of your asyncTask
3) in class A implement onfirstTaskCompleted() and start an new Async task from there.
and repeat the same steps to 2nd and also third async task
You need AsyncTask whenever you want to do an operation asynchronously.
You do the asynchronous part in the doInBackground() of your AsyncTask.
If you can do everything inside a single doInBackground then you need just one AsyncTask.
Such as connect, get data, disconnect.
If you must do 2 separate asynchronous operations then 2 AsyncTasks. Such as connect, get data in one task. Then present them to the user. Then send request to server to delete some data, say, selected the data selected by the user, this you do in another AsyncTask. Or you can use the same asynctask somehow have a different flow of execution in doInBackground for different scenarios.
Related
I used AsyncTask to get html files from server. But when an activity starts, screen becomes white few seconds and displays data when fully downloaded.
I wanted it to display activity's basic layout first(e.g. actionbar) and downloaded data later. So I used Thread and the problem solved.(basic layout is first shown and data later)
I've been knowing AsyncTask do things asynchronously but in my case it didn't.(In doInBackground, I only did network connection)
Does AsyncTask really do things in background?
Does AsyncTask really do things background?
Yes.
Note, though, that AsyncTask is serialized by default, meaning that if you fork multiple AsyncTask instances, they will share a single thread, and the second and subsequent tasks will be queued up waiting until the first task completes. You can avoid this via using executeOnExecutor(), instead of execute(), to run the tasks.
There are other ways of misusing AsyncTask (e.g., calling get()) as well.
I am writing an app that accesses a web site, downloads XML responses and acts on the response.
I have used the solution discussed at How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?, but due to the limitation of AsyncTask only being able to run once, I cannot reuse the AsyncTask for reading the next XML response required. Is AsyncTask the solution for me, or should I be writing my own threaded activity?
There's three ways to do it.
1)Create a new AsyncTask in onPostExecute to do the next task.
2)Create multiple AsyncTasks at the beginning if you already know you'll need another
3)If you know you're going to be reading xml all the time, then a Thread rather than AsyncTask is appropriate.
Background
I have an AsyncTask (call it uploadHeader) that uploads some data to a server.
I have a second AsyncTask (uploadDetail) that uploads some related data, which requires the initial data to have been uploaded: the header upload returns an id issued by the server, which is used to update the local detail records, before they're uploaded.
If at the time uploadHeader was initially called there were connectivity issues, the header info won't have been uploaded.
So at the start of uploadDetail.doInBackground() I check the status of the local header record to see if it has already been successfully uploaded to the server, and if not, call an uploadHeader.get() to upload the header and wait to get the id back, before I upload the detail records.
Problem
It just seems to hang at the get() call. Debugging it, it seems to be creating a FutureTask and then looping somewhere inside that. It looks as if the second AsyncTask is being queued to run after the first one finishes, which it never does since it's waiting on the second.
I've read a number of other posts/articles on calling one AsyncTask from another, but they all seem to be focused on getting the two to run in parallel. I want this to block, until the other task finishes. It's also been mentioned that "execute(Params...) must be invoked on the UI thread.", none of the articles mention get(). Or is get() basically identical to execute() apart for waiting for the result?
As a workaround, I could put the http call to upload the header in a separate class and call that from both uploadHeader and uploadDetail, so uploadDetail wouldn't need to create an uploadHeader task.
I'd just like to understand why it's not working as it is.
get() will block your execution until the second AsyncTask returns a value, don't do this if your first AsyncTask is doing some work that repercutes on the user interface of even in the workflow you've designed.
I'd definitely use Handlers on both AsyncTasks to communicate between them, even another one for the UI if you need to. You may find a good example here. For reference, look here.
So I have an app that will make multipe HTTP Post/Gets
E.G. Login, getThisData, getThatData, sendThis, sendThat
Is it better to have a seperate AsyncTask to handle each one
Or one async task and process them differently with a switch in onPostExecute and doInBackground
Cheers
Short answer is yes you should create a new AsncTask for each call.
And if you interested, the long answer is;
According to the Android's Asynctask documentation,
The goal of the AsyncTask is to take care of thread management for you and you should not worry about the threading mechanisms.
The Android Platform handles the pool of threads to manage the asynchronous operations. AsyncTasks are like consumables. The task can be executed only once (an exception will be thrown if a second execution is attempted.)
Happy asynchronous coding! :-)
It depends on whether the tasks are independent on each other or whether they are interrelated. If independent you can handle this through the same async. For ex if you need some data from your login response and pass that value to getthis task you better use separate async.
Make login a separate async, getthis ,get lthat sendthis sendthat can be in one async.
You'll probably want to separate them, especially if their functionality in the pre/post executes differs. Try to organize your code into logical blocks. For example, if you have an Async Task to Login, and an Async task to, for example, download lots of document data via JSON, they will want separate Async tasks.
However, lets say you have two separate API calls that return similar or partially the same data - if one returned the details of a file (name, size) and the other returned the same data but was a revision of a file - you could switch these in the same ASYNC because the post execute is going to perform the same (or partially the same) code to extract data from the JSON.
If you want to create one instance of AsyncTask, and execute() it several times, no:
Execute AsyncTask several times
If you are asking about designing: whether you should write one class to get different kind of data? It really depends on your circumstances:
If these HTTP call supposed to be sequential, you can put them in one AsyncTask class.
If they have lot in common, just point to different URIs, you can write a call(String uri) method, and invoke that method in your AsyncTask. This case, I think one AsyncTask is also enough.
I need to write a common class for handling http request in the background thread ..i have 4 diffrent ui activities which all wants use the same class to fetch web data and update in their activity... My ui activity wants to just call background class and it should not wait for data..background class only need to post the datato ui thread then ui thread will handle that data... I tried using Asynch task...but it works when i implemented in the same ui class... Can some one give better approach to implement in common class ..and also I have confused between which one to go with asynch task or handler with runnable thread...
Write a service that runs in the background and polls the server for data (use an AsyncTask or some sort of thread to perform the query asynchronously). When data is received from the server, insert it into a local database (a ContentProvider backed by an SQLiteDatabase, for example). Then have the Activity query the local database whenever it needs new data. The advantage here is that you will still be able to display data even when your device is offline... the local database acts as a cache that holds previously-queried data.
As far as I understand AsyncTask has everything you need. Just implement its heir as a standalone class and then use it in your activities.