AsyncTasks in android is the most common when we need to load data. This class allows to perform in background operations and publish results on the UI thread without having to manipulate threads and/or handlers. AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. We need AsyncTask no of time in our app to make call to server and load data in different activity. In this post i create ReUsable AsyncTasks class we use in our project and load data from server we have no need to implement multiple time AsyncTask class to load data from server.

Before you start please read about Dependency Injection in java.

Sample code: ReUsable AsyncTasks class in Android

Step 1. First create new class in your project you create and name that class you like i name that class and copy/paste this code.

*Note: Please use updated class i add updated code at the end of this page.

Above code is easy to understand if you familiar with AsyncTask. In above class i extends AsyncTask and implement its method PreExecute, DoInbackground and PostExecute. I create this class dynamic so i send parameter in this class from outside using its object.

Step 2. Now we need to interface in our project in which we can pass data from class as shown above first i create a object and call its method inside onPostExecute() method.

Now create interface like this

Step 3. Now every thing we need is done, we call this class any where in our project where we need AsyncTask.  Here how i call this class in my project.

Hope this helps a lot in your project.Please comment if any issue you face implementing this in your project.


Updated AsyncTask Class with Timeout feature dialog box null pointer exception issue and other update:-)