An Idiot’s guide to Android AsyncTaskLoader

sanjeev yadav
Sep 13, 2017 · 2 min read

Step by step tutorial on how to define and use AsyncTaskLoader.

This class performs the same function as the AsyncTask, but a bit better. It can handle Activity configuration changes more easily, and it behaves within the life cycles of Fragments and Activities.

  1. Implement LoaderManager.LoaderCallbacks<String> on MainActivity and override unimplemented methods onCreateLoader, onLoadFinished and onLoaderReset

2. Inside onCreateLoader() return a new AsyncTaskLoader<String> as an anonymous inner class with this as the constructor's parameter and override loadInBackground & onStartLoadinginside anonymous inner class

3. In your MainActivity define two constant

//TODO: (1)Integer constant to uniquely identify our Loader
//TODO: (2)String constant which will act as a key to pass data to   Loader

4. Inside loadInBackground make a network call using HTTPUrlConnection or OKHttp or any other library. You can perform any task that can potentially block the main UI thread here.

5. Inside onCreate initialize the loader with OPERATION_SEARCH_LOADER as the ID, null for the bundle, and this for the context

6. Now call this method, whenever and wherever you want to trigger the loader

//your call will look like this
//makeOperationSearchQuery("https://jsonplaceholder.typicode.com/posts");

SuperCharging(Caching) your Loader.

To handle the orientation change and avoiding creating duplicate request follow these steps.

//TODO: (1)Create a member variable inside AsyncTaskLoader to store the cached result in
//TODO: (2)Modify onStartLoading to just call deliverResult if the cache isn't null
//TODO: (3)Override deliverResult to store the data in our cache member variable

And we are done! Please if you find this article intriguing or helpful do share and like. Meanwhile checkout other articles in this series.

To know more about AsyncTask vs AsyncTaskLoder

sanjeev yadav

Written by

Front end & Android Developer, in deep love with learning about CS and a travel enthusiast :)