why should we use onProgressUpdate() method in Asynctask class,
i am using onPreExecute() and onPostExecute() along with doInBackground() but never used onProgressUpdate,In which cases we will use this method.
Thanks in Advance for your response.
onProgressUpdate(Progress...), invoked on the UI thread after a call
to publishProgress(Progress...). The timing of the execution is
undefined. This method is used to display any form of progress in the
user interface while the background computation is still executing.
For instance, it can be used to animate a progress bar or show logs in
a text field.
As you read, you can publish your async task progress by using this.
protected void onProgressUpdate(Integer... progress) {
showProgressPercent(progress[0]);//write your own codes
}
Source
onProgressUpdate() is used to better the user experience by updating the user about the background process initiated at some time. For more information, refer to the docs.
AsyncTask lifecycle : onPreExecute -> doInBackground -> onPostExecute
onPreExecute is calling on MainThread. which means you can touch views.
doInBackground is calling on BackgroundThread. which means you can't touch views.
onPostExecute is calling on MainThread.
so while your job is going on inside doInBackground, you may want to notify user about job's progress but you can't notify user because it's calling on BackgroundThread. you need to jump to MainThread and AsyncTask provides you onProgressUpdate function to make it.
you can call publishProgress inside doInBackground.
Related
I am not sure if this question has been asked on SO before. When executing an async task using myTask.execute(); what method runs at the very beginning. I am following this tutorial: http://mobiforge.com/developing/story/consuming-json-services-android-apps for consuming JSON services and the author is using new ReadWeatherJSONFeedTask()
.execute() along with some parameters. I am confused as to which method runs first and how the parameter are being passed along to get the result.
Can anyone help me.
Thanks.!
Parameters that the asyncTask needs, are declared while defining the class that extends asyncTask.. And the sequence of execution of methods is:
onPreExecute() ---it runs on the UI thread
doInBackground() and onProgressUpdate() -- they run on worker thread
and onPostExecute() --- runs on UI thread.
According to Android API Reference AsyncTask,
When an asynchronous task is executed, the task goes through 4 steps:
onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance
by showing a progress bar in the user interface.
doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used
to perform background computation that can take a long time. The
parameters of the asynchronous task are passed to this step. The
result of the computation must be returned by this step and will be
passed back to the last step. This step can also use
publishProgress(Progress...) to publish one or more units of progress.
These values are published on the UI thread, in the
onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is
undefined. This method is used to display any form of progress in the
user interface while the background computation is still executing.
For instance, it can be used to animate a progress bar or show logs in
a text field.
onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background
computation is passed to this step as a parameter.
As this explains onPreExecute() on Ui Thread is executed at the very beginning.
This Guide might help you with more help in this regard.
I used AsyncTask to request for a large chunk of data. When received, the data is processed inside the onPostExecute method. It may take a while to process the data.
Based from my understanding, AsyncTask is asynchronous and is independent from the UI.
Why does my Activity freezes onPostExecute?
Is it normal for an Activity to freeze if processing inside the onPostExecute method is too long?
How do I make it such that my Activity won't freeze onPostExecute?
You should do all your datasource operations like(database , network ,parsing the response.etc) in doInBackground method.
If you want update any ui updation in async task the use onProgressUpdate
I think you are performing any parsing operations in onPostExecute. try getting filtered or parsed data (lighter data) in onPostExecute.
Why does my Activity freezes onPostExecute?
According your post, you perform some time consuming operation on
PostExecute method. On PostExecute is running on UI thread, so it's
okay that you UI is freezed.
Is it normal for an Activity to freeze if processing inside the onPostExecute method is too long?
Yes, it's. You should perform long operation in doInBackground method
(non-UI thread)
How do I make it such that my Activity won't freeze onPostExecute?
Try to transfer your long time operation to doInBackground method and
in PostExecute just update UI according response, which you get after
operations in doInBackground method.
see Long Running Task You Need to Bind in doInBackground here you cannot Bind UI control Like Button, ImageView etc. After completion of doInBackground in onPostExecute you can Bind All Require Control, make sure here[onPostExecute] you not runnning Another task.
Make sure you are using doInBackground method in your AsynTask method.
I'm very new to programming and I have some doubts.
I have a AsyncTask which is I call as RunInBackGround.
and I start this process like:
new RunInBackGround().execute();
But I wish to wait until this call is finish its executing, before proceeding to the other statements of code.
How can I do that?
Are there any way for it?
wait until this call is finish its executing
You will need to call AsyncTask.get() method for getting result back and make wait until doInBackground execution is not complete. but this will freeze Main UI thread if you not call get method inside a Thread.
To get result back in UI Thread start AsyncTask as :
String str_result= new RunInBackGround().execute().get();
Although optimally it would be nice if your code can run parallel, it can be the case you're simply using a thread so you do not block the UI thread, even if your app's usage flow will have to wait for it.
You've got pretty much 2 options here;
You can execute the code you want waiting, in the AsyncTask itself. If it has to do with updating the UI(thread), you can use the onPostExecute method. This gets called automatically when your background work is done.
If you for some reason are forced to do it in the Activity/Fragment/Whatever, you can also just make yourself a custom listener, which you broadcast from your AsyncTask. By using this, you can have a callback method in your Activity/Fragment/Whatever which only gets called when you want it: aka when your AsyncTask is done with whatever you had to wait for.
In your AsyncTask add one ProgressDialog like:
private final ProgressDialog dialog = new ProgressDialog(YourActivity.this);
you can setMessage in onPreExecute() method like:
this.dialog.setMessage("Processing...");
this.dialog.show();
and in your onPostExecute(Void result) method dismiss your ProgressDialog.
AsyncTask have four methods..
onPreExecute -- for doing something before calling background task in Async
doInBackground -- operation/Task to do in Background
onProgressUpdate -- it is for progress Update
onPostExecute -- this method calls after asyncTask return from doInBackground.
you can call your work on onPostExecute() it calls after returning from doInBackground()
onPostExecute is what you need to Implement.
I think the easiest way is to create an interface to get the data from onpostexecute and run the Ui from interface :
Create an Interface :
public interface AsyncResponse {
void processFinish(String output);
}
Then in asynctask
#Override
protected void onPostExecute(String data) {
delegate.processFinish(data);
}
Then in yout main activity
#Override
public void processFinish(String data) {
// do things
}
I am using AsyncTask to upload data to UI. i wrote the code to download data from server in a separate method and i am calling that method from doinBackground. It will give error because UI methods can't access from doInBackground.but, i want to access . any alternative process is there to access the UI method from doinBackground.?
any alternative process is there to access the UI method from doinBackground.?
Call publishProgress() in doInBackground(). Put your UI-updating logic in onProgressUpdate() of your AsyncTask. onProgressUpdate() will be called on the main application thread (a.k.a., UI thread) after you call publishProgress(). Here is a sample project demonstrating this.
Call runOnUiThread(Runnable action)
more here
Use doInBackground() just for tasks that :
Take some time
Are not UI related
Then you can implement AsyncTask.onPostExecute() to run code to handle those results on main UI thread from AsyncTask
From JavaDoc for AsyncTask.onPostExecute():
"Runs on the UI thread after doInBackground. ... "
As the others have pointed out, you can use runOnUiThread. But, it seems a little odd that you would want to do that in your doInBackground. If you are wanting to indicate progress to the user you would want to handle that in AsyncTask.onProgressUpdate and call publishProgress in your doInBackground.
You can read more about AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html
-Dan
I am doing data fetch from net in an external task.
Now this fetch happens in two steps. So I want to display some message after the first step.
This will happen in the async task not on the UI task.
On the main UI task I already have a progress bar in the preexecute method.
I would like to know if there is a way to display something from the background async task.
I saw handle to be used for threads. Do we have something similar for async task?
AsyncTask has an onProgressUpdate method which runs on the UI thread. Couldn't you use that somehow?
You have to Override the onProgressUpate Method of your AsyncTask. There you can do the stuff to Display the Text.
To trigger onProgressUpdate you have to call publishProgress() in your doInBackground-Method.