How to avoid making a lot of asynkTask class for calling single hit in android

Updated 22 December 2016

Save

In android, When we want to get data from web server then we have to send some request to the server by web services for transferring files such as XML and JSON and HttpTransportSE for a hit to the server.

If you are making any e-commerce app or anything where you have to get the response from different-different API functions then you have to make many asyncTask for calling to the server and getting the response to the server.
For example – We are making an app where we have 3 activity(activity1, activity2, activity3)activity1 is for getting home data by getHome() apiFunctionName, activity2 is for getting some category data by getCategory() and activity3 for showing productData by showProduct() apiFunctionName.

 

activity1.java

 

activity2.java

 

activity3.java

 

Above code will be working well. We can see that for getting 3 api function data from server we have to write  20- 30 line of code in each class for hitting the server.

But if I want to get more and more tasks to retrieve (in different ways) data from the internet and I will not be liking to increase the different classes for each single call.

So avoiding to create multiple classes for each single call, we use Reflection Technique.

I have made a method to prevent increasing of different classes to call the single hit. I have made single async task class and passed functionName and context of the activity and returned response by onPostExecute.

The async task class is there-

AsyncTaskConnection.java

and in caller class(activity1,activity2,activity3)

activity1.java

replace

to

and make response function to your class

Like this-
activity1.java

activity2.java

activity3.java

By using reflection method, we can avoid writing different classes for each single call.
Simply we have to pass context of the activity, API function name and data to send in JSON form.
And get the response where your want.

 

 

 

 

 

 

 

 

 

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home