Android : AsyncTask in fragment – Best pratices

This article shows you how to code properly an asynctask inside a fragment. This is an update of the article Android : AsyncTask – Best pratices that shows you how to code an asynctask with an activity. With a fragment, it is much simplier because you don’t have to manage rotation as the fragment can be set to retainInstance and survive on configuration changes (rotation).

My way to code an async task inside a fragment

The asyncTask is declared as a member of the fragment. A weak reference is used so that the fragment and the async task are loosely coupled. If you don’t use a weak reference, the async task will not be garbage collected because the fragment maintains a reference to it.

public class MyFragment extends ListFragment {

    private WeakReference<MyAsyncTask> asyncTaskWeakRef;

In the onCreate method, we configure the fragment instance to be retained on configuration change. Then, we start the async task.

public void onCreate(Bundle savedInstanceState) {


Below the method to start the async task :

private void startNewAsyncTask() {
    MyAsyncTask asyncTask = new MyAsyncTask(this);
    this.asyncTaskWeakRef = new WeakReference<MyAsyncTask >(asyncTask );

This method may be useful to test if the async task is running or not :

private boolean isAsyncTaskPendingOrRunning() {
    return this.asyncTaskWeakRef != null &&
          this.asyncTaskWeakRef.get() != null &&

Finally, here’s the template code for the async task. This is an inner class of the fragment.

private static class MyAsyncTask extends AsyncTask<Void, Void, Void> {

        private WeakReference<MyFragment> fragmentWeakRef;

        private MyAsyncTask (MyFragmentfragment) {
            this.fragmentWeakRef = new WeakReference<MyFragment>(fragment);

        protected Void doInBackground(Void... params) {

                        //TODO: your background code
            return null;

        protected void onPostExecute(Void response) {
            if (this.fragmentWeakRef.get() != null) {
                             //TODO: treat the result
Share Button


3 Responses to “Android : AsyncTask in fragment – Best pratices”

  1. Marta on July 26th, 2013 10:48 am

    Thank you so much!
    This tutorial helped me a lot! :)

  2. Rodo on August 10th, 2013 6:55 pm

    Thank you for the tutorial.
    A question: Where should I put Asynctask, under onCreateView()?
    What I want to manage is to download and parse an URL in doInBackground() and display the content in onPostExecute() (like in your example, everything iside the Fragment). Thanks in advance for your help.

  3. Michenux on August 11th, 2013 8:21 am

    I think you should do it in the onCreate or onCreateView method. But i would not do that way, i would use Google volley. It’s a great library to deal with network calls. It is easier than using asynctask.

Leave a Reply