1. Are you ready for the Galaxy S20? Here is everything we know so far!

Calling Activity From Async Class

Discussion in 'Android Development' started by VMCG, Mar 25, 2016.

  1. VMCG

    VMCG Lurker
    Thread Starter

    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');

    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();

    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.

  2. Deleted User

    Deleted User Guest

    The way I would tackle this is to define a callback interface, something like this

    Code (Text):
    2. interface ResponseHandler {
    3.   public void handle();
    4. }
    Then make your various classes implement this e.g.

    Code (Text):
    2. class LoginActivity extends Activity implements ResponseHandler {
    3.   ...
    4.   public void handle() {
    5.     ...
    6.   }
    7. }
    9. class OrderActivity extends Activity implements ResponseHandler {
    10.   ...
    11.   public void handle() {
    12.     ...
    13.   }
    14. }
    The final piece is to pass in your Activity object to the APIRequest when you construct it

    Code (Text):
    2. APIRequest request = new APIRequest(loginActivity);
    You APIRequest constructor is declared like this

    Code (Text):
    2. public APIRequest(ResponseHandler handler) {
    3.   ...
    4. }
    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.
    #2 Deleted User, Mar 25, 2016
    Last edited by a moderator: Mar 25, 2016

Share This Page