• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Calling Activity From Async Class

VMCG

Lurker
I'm building an app that relies heavily on REST calls to our web server.

I've build a class API that manages the requests, which has a sub class
APIRequest extends AsyncTask to preform the REST calls.

Here is some sample code

API request = new API();
request.addParam('name', 'John');
request.send('account/update');

The send method is straight forward and calls the Async task which runs on a seperate thread.

public void send(String uri) {
APIRequest request = new APIRequest();
request.execute(uri);
}

The app will rely heavily on this API class so I need some way for the Async method
onPostExecute to call different methods. For example when I want to use the API class for login, I want it to call a method in my LoginActivity class, but if I want to pull down orders I want it to call a method in my OrderActivity class.

I think the right way to do it is that when I call my send() method I want to be passing in a function or some sort of instruction on what to call when the thread is done.
 
The way I would tackle this is to define a callback interface, something like this

Code:
interface ResponseHandler {
  public void handle();
}

Then make your various classes implement this e.g.

Code:
class LoginActivity extends Activity implements ResponseHandler {
  ...
  public void handle() {
    ...
  }
}

class OrderActivity extends Activity implements ResponseHandler {
  ...
  public void handle() {
    ...
  }
}

The final piece is to pass in your Activity object to the APIRequest when you construct it

Code:
APIRequest request = new APIRequest(loginActivity);

You APIRequest constructor is declared like this

Code:
public APIRequest(ResponseHandler handler) {
  ...
}

Alternatively, you could modify the send method to take ResponseHandler parameter, in addition to the URI.

So when the call to the web service completes, the handle() method can be called, using whichever type of Activity object you passed in to the constructor.
 
Last edited by a moderator:
Back
Top Bottom