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.

@Override
public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setRetainInstance(true);
        startNewAsyncTask();
}

Below the method to start the async task :

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

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 &&
          !this.asyncTaskWeakRef.get().getStatus().equals(Status.FINISHED);
}

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

        @Override
        protected Void doInBackground(Void... params) {

                        //TODO: your background code
            return null;
        }

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

Comments

Leave a Reply