This question already has an answer here:
I have the following asynctask class which is not inside the activity. In the activity I'm initializing the asynctask, and I want the asynctask to report callbacks back to my activity. Is it possible? Or does the asynctask must be in the same class file as the activity?
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
caller.sometextfield.setText("bla");
}
Something like this?
I will repeat what the others said, but will just try to make it simpler...
First, just create the Interface class
Second, create the AsyncTask (which can be an inner static class of your activity or fragment) that uses the Interface, by including a concrete class. In the example, the PostTaskListener is parameterized with String, which means it expects a String class as a result of the async task.
Finally, the part where your combine your logic. In your activity / fragment, create the PostTaskListener and pass it to the async task. Here is an example:
Done!
I felt the below approach is very easy.
I have declared an interface for callback
Then created asynchronous Task for responding all type of parallel requests
Then Called the asynchronous task when clicking a button in activity Class.
Thanks
You can create an
interface
, pass it toAsyncTask
(in constructor), and then call method inonPostExecute()
For example:
Your interface:
Your Activity:
And your AsyncTask:
EDIT
Since this answer got quite popular, I want to add some things.
If you're a new to Android development,
AsyncTask
is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:Activity
, it will stay in memory even after user left the screen (or rotated the device).AsyncTask
is not delivering result toActivity
ifActivity
was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.Activity
When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.
IN completion to above answers, you can also customize your fallbacks for each async call you do, so that each call to the generic ASYNC method will populate different data, depending on the onTaskDone stuff you put there.
Remind: I used interface on the main activity thats where "Main" comes, like this:
My API post execute looks like this:
The API constructor looks like this: