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.
Related
Basically title. I can run them all in a row or all at once. I need the first one to run to load data for the rest.
Any ideas?
Maybes using handler for the first one so that the code runs on a different thread and trigger the rest when that one completes:
Handler firstTask = new Handler(new Runnable() {
Run() {
//do code
//run rest of tasks
}
}
If you want to make sure that the first AsyncTask has finished and returned the required data before the rest are executed, then override the onPostExecute() method of the first AsyncTask and execute the remaining AsyncTasks inside it.
onPostExecute() is a methode called after the AsyncTask is finished, you can check for the correctness of the received data inside it before executing the other AsyncTasks also inside it.
Your AsyncTasks will be run in the order in which they are submitted and not concurrently, unless you explicitly use the ExecuteOnExecutor method. You can pass data between them accordingly.
Just to be clear, you don't have to do anything at all to make sure that the first task completes before the second (and so on) are run. Each will complete before the next is started, in submission order.
I am doing a geocoding get request using AsyncTask which needs to finish executing, before proceeding to call another AsyncTask which will use the results from the geocoding request to make another call to another endpoint from the MainActivity.
I thought about forcing it to loop in a while using a "done" flag, set by the first AsyncTask, that may not even work however and it seems very hacky. Does anybody have an idea how to handle this?
AsyncTasks have the hook method onPostExecute(), where you can process its results.
From there, you can simply trigger any methods you want to be executed after the AsyncTask is finished.
For example:
protected void onPostExecute(Long yourResult) {
processYourResult(yourResult);
// Method startMoreLogic() will be executed after the AsyncTask is finished.
startMoreLogic();
}
make your asynctask as a private class and put everything that wait for result at onPoseExecute().
Or add .get() to the method where you call your asynctask.
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.
I have an activity that displays a number. The number is obtained from SharedPreferences e.g
int num=pref.getInt(myAsyncTask.MYNUMBER,0);
The SharedPreference is loaded inside an AsyncTask where calculations take place (that involve retrieving data from db and so on). So, OnCreate() of the activity I run the Asynctask to calculate the value. However, the value is not always updated to the latest one when I launch the activity. This might be because Asynctask takes more time to calculate the new value than the the action of displaying the value inside the activity. How can I delay the execution of the method displaying the value until the Asynctask finishes with the process of the new one?
[[EDIT]]
I removed sharedpreferences. I use the onPostExecute() method to get the result. However, the behaviour is similar. The result is returned after the value is displayed so i couldn't see anything at all.
If the calculation doesn't take more than few second, the simplest solution is to use AsyncTask.get(), this method will block UI thread execution and make UI thread waiting for AsyncTask to finish:
public void onCreate(Bundle savedInstanceState) {
... ...
MyAsyncTask myAsyncTask = nee MyAsyncTask();
myAsyncTask.execute();
myAsyncTask.get(); // alternatively you can use AsyncTask.(long timeout, TimeUnit unit)
... ...
}
Bear in mind that it blocks UI thrread execution, if your calculation is longer than 5 seconds, you will probably get ANR exception.
Since you already use AsyncTask, a more reasonable solution is moving execution of the method displaying the value into AsyncTask.onPostExecute(), this is the exactly reason why AsyncTask exist in API to solve this kind if scenario.
Just use listener concept, or just 'pass' your Activity to your asynctask so It can call the main thread.
If the value is not showing as correct at the time you launch the activity you should set the visibility of the View to View.GONE so it doesn't appear, then change the visibility back to visible when you have the result. To update the value you could implement a listener on your activity that gets called by the AsyncTask.
If its going to take a significant time (more than a few seconds) you might want to also use a progress dialog so the user understands that they need to wait.
I have an API in one jar that uses AsyncTask to carry out some work in the background. I need to wait for the result to be returned and then do some more wok with this result.
I signal back to one class in onPostExecute() method and then the result is handled on the UI thread, but the handler needs to be defined as a callback in a different project altogether so I can't just do the work in the onPostExecute.
In the second project I need to wait for the AsyncTask to end AND for the response to be handled, then I need to display the results of the handler to a TextView in an activity in the second project.
Thread.sleep and using a CountDownLatch don't work because the handling is done in the UI thread. Is there any way to do such a thing?
If I understand correctly, you have AsyncTask in one jar and UI that needs to be updated in another jar. If you run them as one application it should not matter where they are located. Since you mentioned that some callback is involved you can just execute this callback in onPostExecute.
The following will be an approximate sequence of events
Activity from jar 2 creates async task and passes callback that knows how to update TextView as parameter to constructor
AsyncTask stores callback in instance variable
Activity executes AsyncTask
AsyncTask in onPostExecute calls method on callback with appropriate parameters
Callback updates TextView