Basic ASyncTask assistance - android

Okay, I've read the Android documentation and been perusing article after article on ASyncTask and just don't understand how to get information back from my external ASyncTask class. This runs fine:
myASyncTask = new MyASyncTask();
myASyncTask.execute(myParam);
...and I fully expect the task to complete but how do I get anything back from it? The documentation says that onPostExecute is invoked on the UI thread but it also says to not call onPostExecute manually?!? How do I get data back from my ASyncTask object???
I've got it to work fine when I create my ASyncTask as an inner class but I'd rather this task be external so I can call it from different Activitys.

If you read the documentation you can use get method to get the result , and it waits till the task is done .
You can also use getStatus to get the current status of the task , assuming it publishes it .

Related

ReExecute AsyncTask

I have several AsyncTask in my Project to grab data from some given apis.
I followed the following steps.
1) execute an Async Task and try to grab datas from there.
2) check conditions for internet and server down
3) if any issue in api or internet or server then show dialog [custom from self made class]
4) dismiss button for canceling the dialog and go back to the working stage of `app may be even by closing the activity`
My problem is I want to keep a Button "Retry" such that it shall be re executing the AsyncTask.
I searched of passing AsyncTask but it seemed worthless as I concluded AsyncTask cannot be passed. And so I am forced to repeat same code cancel(true) for various times
It would be very useful if anyone could give me solution for it with this code re-use concept.
You cannot "retry" the same AsyncTask object - you can only call AsyncTask#execute() once. However, you could create a new AsyncTask instance when the user decides to retry the download task.
Solved The problem by using a retry button that creates the new object of class implementing Async-task and executing that new object.

Generic AsyncTask with Error Handling and progress dialog

please tell me best way to write this.
I need one generic AsyncTask for webservice call with all possible errror handling. Also a callback for updating UI/ showing error message.
I have found few approches :
by adding Generic parameter to async task
making asynctask as abstract
for handling error giving handler object.
This is actually very easy to do with an AsyncTask.
AsyncTask has 4 functions. 3 of them run on the UI Thread so you can update the UI as much as you like. 1 of the functions runs in the background so you can do things that take as long as is necessary, such as calling your webservice.
You do not need a formal callback function. AsyncTask.onPostExecute() handles this for you.
There is a great example in the Android documentation that shows how to download a file exactly as you are trying to do with the webservices connection. You will extend AsyncTask and create your own DownloadFilesTask just like in the example.
The whole thing is started with a single line of code:
new DownloadFilesTask().execute(...)
The four functions are:
onPreExecute() - Useful for displaying a ProgressBar or other
UI elements.
doInBackground() - Take as long as you want, but don't update
the UI from here. Instead, call publishProgress() as often as you
like. That will internally call onProgressUpdate() where you can
incrementally update the UI, or your ProgressBar, if you want.
onProgressUpdate() - Optional show progress updates or increment
a ProgressBar. This function only gets called in response to calling
publishProgress() from doInBackground().
onPostExecute() - Done, dismiss() your ProgressBar, update
the UI, process any errors saved in doInBackground(), and jump to
the next section of your code.
Error Handling:
All errors are trapped in doInBackground(). You should save an int errorCode and/or String errorMessage in your DownloadFilesTask class, and return; from doInBackground() when an error occurs. Then, process and report the error in onPostExecute().
See this question for several answers. They all involve storing any exception thrown by doInBackground in a field and checking it in onPostExecute. I like this answer posted by #dongshengcn, which encapsulates this into a subclass of AsyncTask, then you can override onResult and/or onException as necessary.

Async task - not clear re called methods

I have a a service class which includes an Async task. In the doInBackground and onPostExecute I call some methods which are in the service class but outside the Async task. When these methods get called will they still be in the thread created by the Async task and therefore not interfering with the main UI.
To illustrate my lack of understanding a bit more should I try to get almost everything that the service class does into the Async task. For example the service starts up as the result of an alarm and in the onStartCommand sets a repeating alarm (this is as Reto Meire's Earthquake example)and creates a database. Would it make sense to move the code for these two operations into the onPreExecute part of the Async task?
No need to do that.. make sure that the method which you want to run in background is called from doInBavkground().. rest you can put in postExecute.... the snippet which you want to run after the backGround task should be in PostExecute(). If You call methods from doInBackground() they still run on background thread.. does't matter where they are.. and if you call it from onPostExecute() then it will run on other thread which ofcourse can make changes in your display.. just like showing dialog etc...
You should always offload as much work as possible to background threads/tasks. Something like database creation should be done in the doInBackground method. The onPreExecute and onPostExecute methods run on the UI thread and are generally used to inform the user of background activity (e.g. using a ProgressDialog).
From experience, I also suggest not using a background service if you can get away with it. If you use one, you should know how to clean it up properly since users generally get annoyed with an application running in the background.

Using AsyncTask inside Activity to perform multiple tasks

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.)

Android 1.5: Asynctask doInBackground() not called when get() method is called

I am running into an issue with the way my asynctasks are executed. Here's the problem code:
firstTask = new background().new FirstTask(context);
if (firstTask.execute().get().toString().equals("1")) {
secondTask = new background().new SecondTask(context);
}
What I'm doing here is creating a new asynctask object, assigning it to firstTask and then executing it. I then want to fire off a separate asynctask when the first one is done and making sure it returns a success value (1 in this case).
This works perfectly on Android 2.0 and up. However, I am testing with Android 1.5 and problems start popping up. The code above will run the first asynctask but doInBackground() is never called despite onPreExecute() being called. If I am to execute the first task without the get() method, doInBackground() is called and everything works as expected. Except now I do not have a way to determine if the first task completed successfully so that I can tell the second task to execute.
Is it safe to assume that this is a bug with asynctask on Android 1.5? Especially since the API (https://developer.android.com/reference/android/os/AsyncTask.html#get%28%29) says that the get method has been implemented since API 3.
Is there any way to fix this? Or another way to determine that the first task has finished?
If you are going to block (via get()), why are you bothering with AsyncTask in the first place? The whole point of AsyncTask is to not block.
If you want to have SecondTask execute when FirstTask is done, have FirstTask execute SecondTask in FirstTask's onPostExecute().

Categories

Resources