AsyncTask Class

116 views Asked by At

i am working on my android project & want a little help. I have two classes . one of them is an AsyncTask class which is used to connect to web server for downloading some information & other one is an Activity Class which is used to display these information. i think my problem is clear and was asked by many developers before.i don't know how to return these information to the Activity class! I used to create AsyncTask class inside of Activity class & With this method , i was able to put the result in the variables of Activity Class but after a while i found it was against of OOP's concepts so i need to separate these two classes.

Fact

AsyncTask class has two important methods . the first one is doInBackground which prepares the result. after that in onPostExecute you can manipulate the result .

what have i tried to achieve this goal ?

Actually i searched google but didn't find anything useful! there was only one attractive solution which was accepted although i couldn't use it! it suggests creating an interface class but it was not clear.Do you think , it is the only solution ? Do you have any solution for my problem ?

2

There are 2 answers

1
nitish516 On

Create an interface and implement it in Activity.

public interface AsyncResponse {
    void processFinish(String output);
}

In AsyncTask class

public AsyncResponse delegate=null;


@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    delegate.processFinish(result);
}

In activity implement interface

Activity implements AsyncResponse {task = new AsyncTask();
           task.execute();
           task.delegate = this; @Override
public void processFinish(String output) {// you got output here  }}
0
ALearner On

A Handler is particular useful if you have want to post multiple times data to the Activity from Asynctask.

A Handler object registers itself with the thread in which it is created. For example, if you create a new instance of the Handler class in the onCreate() method of your Activity, the resulting Handler object can be used to post data to the Acvity/main thread.

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

You can create Handler Instance and override the handleMessage method. Pass the Handler reference to the Asynctask to send message from onPostExecute.