Sending Request and Receiving Response from Network now made simpler with Volley Integration

Contributed by Kunal Kant Tiwary on 30 Oct 2013

We, at Neev, have been working on Android application development for more than four years. The task of Networking which involves sending requests and handling responses from web service is both time consuming and effort consuming.

Why so?
1. We need to create a method that can accept requests and send us back the response.
2. In Android, every I/O task needs to be performed in a different thread and not in the UI thread. Thus, we use “AsyncTask” provided by Android SDK.
3. In the method “onPostExecute()”, we manage the response according to the requirement.

The problem with the above steps is that, in order to achieve perfect results, we need to write a large number of lines of code. If we start a ‘AsyncTask’ for a web service request from Screen-A but before reaching onPostExecute() of this ‘AsyncTask’, we switch to Screen-B, then the original Web Service request is rendered redundant. This results in performance issues such as slowing down of the data transmission speed. Since onPostExecute() is working, the Web Service Response is no longer required.

The solution to these issues is to cancel the AsyncTask. However, this could result in inconsistency in our code.

Now, what if we have a library which does all this? What if we no longer have to use AsyncTask or a common class to handle the requests and responses? Instead, What if we get only the callbacks like ‘onResponse()’ or ‘onError()’?

Volley, a library provided by Android, takes care of these ‘what ifs’. We need to focus on some callback methods.

There are few steps to be followed to integrate Volley Integration Library:
1. Import Volley Integration Project in your existing project workspace.

2. Add Volley Integration Library in your Project.

3. Initialize Network Manager in Application class.
Code Snippet:
public class MainApplication extends Application {
@Override
public void onCreate() {
init();
super.onCreate();
}
private void init() {
NetworkManager.init(this);
}
}

4. Implement RequestListener in Activity or Fragment where you have any HTTP Request call.
Code Snippet:
public class MainActivity extends Activity implements RequestListener

5. Get Instance of RequestManager.
Code Snippet:
RequestManager instance = RequestManager.getInstance();

6. Register your RequestManager instance to RequestListener.
Code Snippet:
instance.setRequestListener(this);

We hope you find Volley useful just like we did.
- Contributed by Kunal Kant Tiwary

Visit us at Neevtech.com to know more about our offerings.

Tags: , , , , , , , , , , , , , , , , , , ,

facebook comments:

Leave a Comment

Security Code: