Search code examples
androidclassandroid-fragmentsandroid-asynctaskcode-reuse

How to return an variable from a AsyncTask class to an fragment


I have created an multiple fragments which all require data from an server. So I created an reusable AsyncTask. Which connects to an server via sockets, transfers some packets and finaly receives the response. How can I 'dynamically' return the result (a.k.a the response) from onPostExecute? I have created an flowchart to explain myself better.

How to return an variable from a AsyncTask class to an fragment flowchat


Solution

  • The AsyncTask can simply call a callback in the provided Fragment in onPostExecute, or the AsyncTask can be a nested class of the given fragment.

    for example

    public class MyFragment extends Fragment {
    
        void onResult(Result result) {...}
    
        private class MyTask extends AsyncTask<String, Void, Result> {
            doInBackground(...) {}
            onPostExecute(Result result)  {
                onResult(result);
            }
        }
    }
    

    This has the drawbacks of holding the reference of the fragment until your task is complete. If your task always terminates eventually and is not referenced by any static context, then it's fine since the memory will eventually be collected.