{"id":504,"date":"2015-10-24T21:43:03","date_gmt":"2015-10-24T21:43:03","guid":{"rendered":"http:\/\/installingcats.com\/?p=504"},"modified":"2015-10-24T21:43:03","modified_gmt":"2015-10-24T21:43:03","slug":"android-asynctask-return-result","status":"publish","type":"post","link":"https:\/\/installingcats.com\/2015\/10\/24\/android-asynctask-return-result\/","title":{"rendered":"Android AsyncTask return result"},"content":{"rendered":"

To get Android AsyncTask to return a result use a callback method (Observer pattern) by following these steps.<\/p>\n

    \n
  1. Define\u00a0a constructor for our async class which extends AsyncTask (we’re required to subclass\/extend AsyncTask for use). Let’s call our AsyncTask class MyAsyncTask.<\/li>\n
  2. Constructor\u00a0parameter takes a class which will handle the AsyncTask result. \u00a0Usually an Activity or Fragment, but could be a Robolectric Unit Test class for example.<\/li>\n
  3. Declare a member variable\/private field to hold the handling Activity\/Fragment\/Test. We’ll call it ResultListener. \u00a0The constructor will assign its parameter input to this member variable.<\/li>\n
  4. Declare an Interface within \u00a0MyAsyncTask. Let’s call it ResultListener<\/li>\n
  5. ResultListener defines a single method that our handling class must implement. \u00a0Let’s name the method handleAsyncResult and in this case it’s going to take a single boolean as an input parameter.<\/li>\n
  6. In onPostExecute, call our listener class handler method, supplying a value to the\u00a0input parameter as appropriate for the outcome of doInBackground.<\/li>\n<\/ol>\n

    Here’s a concrete example of an Android AsyncTask returning a result:<\/p>\n

     <\/p>\n

    public class MyAsyncTask<T> extends AsyncTask<T, Void, Boolean> {\n    private final String TAG = this.getClass().getName();\n    ResultListener listener;\n\n    public interface ResultListener {\n        void handleAsyncResult(boolean result);\n    }\n\n    WebProxy proxy;\n\n    public MyAsyncTask(ResultListener listener) {\n        this.listener = listener;\n    }\n\n    @Override\n    protected Boolean doInBackground(T... params) {\n        \/\/ do interesting long running things here, Network, database, etc.\n        Log.i(TAG, String.format(\"doInBack: sending %s via Retrofit\", params.getClass().getName()));\n        return true;\n    }\n\n    @Override\n    protected void onPostExecute(Boolean success) {\n        listener.handleAsyncResult(success);\n    }\n}\n<\/pre>\n

    As a bonus this AsyncTask uses a Type parameter <T> as input, so it can handle different input types for the AsyncTask.execute(input). This will make your AsyncTask more reusable and easy to extend for future use.<\/p>\n

    When MyAsyncTask completes doInBackground, it will pass a boolean to onPostExecute which we’re going to send along to our handling class through listener.handleAsyncResult(success).<\/p>\n

    Within our handling class (supplied to our AsyncTask constructor) we’ll need to do two things:<\/p>\n

      \n
    1. Make our class implement our Interface by adding \u00a0“implements MyAsyncTask.ResultListener” after the class name.<\/li>\n
    2. Define a method within our handling class with a signature that matches MyAsyncTask.ResultListener.<\/li>\n<\/ol>\n

      Here’s an example for our implementing class:<\/p>\n

      public class Test implements MyAsyncTask.ResultListener {\nprivate boolean asyncResult;\n\n@Override\npublic void handleAsyncResult(boolean result) {\n    asyncResult = result;\n}\n\n\n@Test\npublic void firstAsyncTest() throws Exception {\n    MyAsyncTask<Checkin> myTask = new MyAsyncTask<>(this);\n    myTask.execute(someArrayOfTypeT);\n    assertThat(asyncResult).isTrue();\n}\n\n}<\/pre>\n","protected":false},"excerpt":{"rendered":"

      To get Android AsyncTask to return a result use a callback method (Observer pattern) by following these steps. Define\u00a0a constructor for our async class which extends AsyncTask (we’re required to subclass\/extend AsyncTask for use). Let’s call our AsyncTask class MyAsyncTask. Constructor\u00a0parameter takes a class which will handle the AsyncTask result. \u00a0Usually an Activity or Fragment, […]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[28,29],"tags":[251],"_links":{"self":[{"href":"https:\/\/installingcats.com\/wp-json\/wp\/v2\/posts\/504"}],"collection":[{"href":"https:\/\/installingcats.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/installingcats.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/installingcats.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/installingcats.com\/wp-json\/wp\/v2\/comments?post=504"}],"version-history":[{"count":0,"href":"https:\/\/installingcats.com\/wp-json\/wp\/v2\/posts\/504\/revisions"}],"wp:attachment":[{"href":"https:\/\/installingcats.com\/wp-json\/wp\/v2\/media?parent=504"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/installingcats.com\/wp-json\/wp\/v2\/categories?post=504"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/installingcats.com\/wp-json\/wp\/v2\/tags?post=504"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}