Using AsyncTask inside Activity to perform multiple tasks - android

Consider this: I've got Activity, in onCreate() I start AsyncTask to load its content. I've followed this sample. Now my problem is: I want to download file in that Activity, using AsyncTask. But I don't know how to make existing AsyncTask do various tasks.
If anyone had the same problem, I would appreciate your help.

Well, I've succeeded to make it call again and again... you have to instantiate your class as a null first (int the Activity).
MyAsyncTask asyncTask = null;
and then put it in a try... catch block:
asyncTask = (MyAsyncTask) new MyAsyncTask().execute(params);
The other thing you're interrested about is the differenc methods you want to run... Well, I wanted to do the same, but I've had no time writing that one, but I've thought about it on the way home from work.
I think your class extending AsyncTask should look like this:
class MyAsyncTask extends AsyncTask<Object, Object, Object> { }
create some variables or ArrayLists in your AsyncTask, and do the decision on the overriden onPreExecute() method where you have to make a switch, or some if's. Do the call/work on the overriden doInBackground(), get the result, and process it in the overriden onPostExecute() method.
I don't know if this line works, since I've had no time to experiment it, I really just thought about it, how to... :)
But I hope the thought helps at least! :)

You must implement two separate AsyncTasks with different doInBackground methods or add file downloading to existing one.
Remember that (from documentation):
The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Related

Get data from more than one AsyncTask in one class?

My situation is this:
first I call first AsyncTask which fetched required Items from database. After that, I call another AsyncTask, which fetches these Item images.
I am getting data from AsynTasks by using callback.
Here is the issue - since I am using callback, in my class I have method processFinish which returns AsyncTask data when it finishes its computation. The problem is with two Async tasks which depend on each other. What should I do now?
You can use the get() method of asyncTask that will wait for the output and wont proceed further
also you can use it with a timeout.
ex new BackgroundTask().execute.get();
or
new BackgroundTask.execute.get(long timeout);
You could execute one AsyncTask inside another, but you should do it inside onPostExecute() because this method runs on the UI thread.
#Override
protected void onPostExecute(Void args) {
new AsyncTask2.execute(..); // Start second task once you've got first results
}
And you call your method processFinish(..) only once, after the second AsyncTask is completed.
Anyway, is there a reason why you use two AsyncTasks ? With your explanations we could believe that you might be able to use only one task.

Android Asynctask Generally Understanding Questions

Android Asynctask Generally Understanding Questions.
If I want to make Asynctask SyncTask, how do I do that?
AsyncTask A = new AsyncTask();
AsyncTask B = new AsyncTask();
A.execute();
B.execute();
If I want A to finish before B starts how should I do that?
If I close an Activity, does the AsyncTask call on that activity gets destroy?
If I close the whole application, does the AsyncTask call on that application gets destroy?
call b.execute() in onPostExecute() of A
AsyncTask is an abstract class so you must extend it in order to add your app specific functionality to it. You implement the doInBackground() method to do what ever work is required. The AsyncTask documentation explains it in detail. I will give a brief answer to each of your question.
If I want to make Asynctask SyncTask, how do I do that?
You have the right idea with creating the async task, however as I mentioned before you have to subclass the async task to actually do some work.
Here is an example (note that the Void types do have meaning however the documentation covers them in great detail)
public class MyTask extends AsyncTask<Void, Void, Void>
{
//This method will run on the back ground thread
#Override
protected Void doInBackground(Void... params)
{
// All the heavy work should be done here e.g.
// loading from network, database etc.
return null;
}
}
Then in your activity you would create and run this task as follows :
MyTask myTask = new MyTask();
myTask.execute()
If I want A to finish before B starts how should I do that?
As the documentation states:
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.
Which means if you are using honeycomb or later async tasks will run on a single thread. So normally A should get executed before B if you execute in that order. But I would do something like this: Launch A, then when onPostExecute() of A gets called, you know that A is done, you can start your task B from this method to be sure that A finishes before B.
If I close an Activity, does the AsyncTask call on that activity gets
destroy?
The short answer to this question is No. The async task will continue to run even if the activity has called on destroy. However if the async task is tied to the activity life cycle you need to make sure you end the task when the activity dies or you will run into problems.
If I close the whole application, does the AsyncTask call on that
application gets destroy?
I am not 100% sure about this one. I believe the behavior is unspecified since now its up to Android to collect resources. It may decide to kill the task right away if its low on resources or it may not. However you should avoid this design. If you need to run something after your application has closed, then look at the Service class.
Take a look at http://www.compiletimeerror.com/2013/01/why-and-how-to-use-asynctask.html#.VNtB1LDF_38 it may help you.

AsyncTask called a lot from many places

I'm using a simple AsyncTask to download the sourcecode of a web page as a String. So far everything works fine.
However, I don't want to always do the same thing with the result String, sometimes I want to fill the gui with it, sometimes I want to parse it, sometimes I want to call more functions with it as a parameter.
Actually, I have more than one activity and more than one class that need to download the sourcecode of a page.
Of course, onPostExecute() is what has to handle the result of my Task, but since it will be called from so many places and for so many different reasons I'm really at a loss.
What can I do?
I really don't want to write 20 AsyncTasks that always do the same thing in their doInBackground(...) with different onPostExecute, nor I want the code from 20 different classes/activity to end up in a single onPostExecute, my code would be so complicated to maintain.
Any suggestion?
Thanks
I would resolve it with the use of interfaces. Make an async task that does the right stuff in the doInBackground and that takes some parameter so that you know what to do in the onPostExecute and pass the parameter and result down to onPostExecute.
then make an interface with a method like handleSourceCodeString(String source); and then implement one class for every action that you want to do. Then put the classes in a map in some init function.
Map<String, Class> myActionMap = new HashMap<String,Class>;
myActionMap.put("parse-soruce", ParseSource.class) //(where ParseSource.class implements your interface)
and then in your postExecute do something like:
((MyActionInterface)myActionMap.get(action).newInstance()).handleSourceCodeString(source);
I found this... love the idea... seems pretty straight forward and better than using interfaces in my opinion.
AsyncTask onPostExecute call from outside the AsyncTask
Look at the first answer

AsyncTask calling main class method, did it work fully in background?

This is my problem..i am calling a method in doInBackground of my AsyncTask class, the method is declared in my main activity class. Does it work in background thread? or i need to write the whole method inside the doInBackground ??
protected String doInBackground(String... params) {
getAllUsersfromServer();
return null;
}
this getAllUsersfromServer(); is declared in the main class. the method download some data from server using REST..
I need to run this whole process in background thread. Does it works?
Does it work in background thread?
AFAIK, Yes it works in background thread.
do I need to write the whole method inside the doInBackground ??
No need to do that.
onPostExecute works very next moment.. even my users information are
still loading
This is the main point, Its just working line by line, when it goes to execute getAllUsersfromServer(); the control goes to execute that method which gets executed in Another Background Thread. [To understand add one log print line below the method call in doInBackground and one in the method's loop and you will see even if the loop doesn't complete the doInBG log will get printed]
This happens because, your method getAllUsersfromServer(); is Void, and the Android takes it as some other independent work to be done and doesn't wait till it gets complete and keep moving to next lines.
Solution :
Just add one return type i.e. boolean getAllUsersfromServer(); and add return statement in the method return true; and in your doInBackground boolean flg = getAllUsersfromServer();
AsyncTask method doInBackground works asynchronously in a separate thread and your main thread remains available to display UI.
However what we usually do is that network processing such as "getAllUsersFromServer" is done using static HttpHelper class or method etc.
Yes it will work in the background thread. check this
I don't know why you would want to do that, but anyhow:
You'll have problems if the activity is destroyed during the async call, like if there's an orientation change. A solution to that would be to make the method static.

AsyncTask inside onPostExecute of AsyncTask?

In an Android activity I'm executing an AsyncTask in onCreate method.
Should I declare the handler function of UI buttons inside onPostExecute of AsyncTask or in OnCreate method? Can I create another AsyncTask inside this button onClick handler? Thanks
A little bit of code would be helpful to better answer you. But the call to the constructor or the execute() method can be done in onCreate() but the actual class should be created either in a separate file or as an inner class of your Activity, depending on what you need it for. What you are explaining would probably work but I wouldn't put onClick events in your AsyncTask. If nothing else, for the readability. Also, this may make it more error prone, in my opinion. You might need local variables outside of the AsyncTask for the onClick() so this would reduce scope issues. Calling an AsyncTask from inside an onClick() would generally be fine to do. I hope this makes sense but if you need more clarification feel free to ask

Categories

Resources