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.
LoaderManager.LoaderCallbacks<String>on MainActivity and override unimplemented methods
onCreateLoader() return a new
AsyncTaskLoader<String> as an anonymous inner class with
this as the constructor's parameter and override
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
loadInBackground make a network call using
OKHttp or any other library. You can perform any task that can potentially block the main
UI thread here.
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.
An Idiot’s guide to Android RecyclerView Part 1
Step by step tutorial on how to define and use RecylerView. Here’s the end preview of what we will make.
To know more about AsyncTask vs AsyncTaskLoder