Android Volley – First Part of Two

Android volley is a networking library which was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls work asynchronously, so developers don’t need to worry about using asynctask anymore. Therefore this would replace the current implementation of JSON parsing.

Volley comes with lot of features. Some of them are

  1. Request queuing and prioritization
  2. Effective request cache and memory management
  3. Extensibility and customization of the library to our needs
  4. Cancelling the requests

Volley excels at RPC-type operations used to populate a UI, such as fetching a page of search results as structured data. It integrates easily with any protocol and comes out of the box with support for raw strings, images, and JSON. By providing built-in support for the features you need, Volley frees you from writing boilerplate code and allows you to concentrate on the logic that is specific to your app.

Volley is not suitable for large download or streaming operations, since Volley holds all responses in memory during parsing. For large download operations, consider using an alternative like DownloadManager.

The core Volley library is developed in the open AOSP repository at frameworks/volley and contains the main request dispatch pipeline as well as a set of commonly applicable utilities, available in the Volley “toolbox.”

The best way to maintain volley core objects and request queue is, making them global by creating a singleton class which extends the Application object. To achieve this, a  controller class was created:

public class AppController extends Application {
    public static final String TAG = AppController.class.getSimpleName();

    private RequestQueue mRequestQueue;
    private ImageLoader mImageLoader;
    private static AppController mInstance;
    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
    }
    public static synchronized AppController getInstance() {
        return mInstance;
    }
    public RequestQueue getRequestQueue() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
         return mRequestQueue;
    }
    public ImageLoader getImageLoader() {
        getRequestQueue();
        if (mImageLoader == null) {
            mImageLoader = new ImageLoader(this.mRequestQueue,
                    new LruBitmapCache());
        }
        return this.mImageLoader;
    }
     public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }
     public <T> void addToRequestQueue(Request<T> req) {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }
     public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}
Volley is shipped with powerful cache mechanism to maintain the requested cache. This saves lot of internet bandwidth and reduces user waiting time. Following is the implementation of the Volley cache methods:
Cache cache = AppController.getInstance().getRequestQueue().getCache();
Entry entry = cache.get(url);

if(entry != null){
    try{
        String data = newString(entry.data, "UTF-8");
        } catch(UnsupportedEncodingException e) {      
        e.printStackTrace();
        }
    }
}else{
}
In the same way, requests can be cancelled, deleted or permanentely switched off. Requests can also be prioritised. The priory can be Normal, Low, Immediate and High, according to which are the most important requests, in the app.
private Priority priority = Priority.HIGH;
StringRequest strReq = new StringRequest(Method.GET,Const.URL_STRING_REQ, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
              Log.d(TAG, response.toString());
              msgResponse.setText(response.toString());
              hideProgressDialog(); 
         }
}, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError error) {
               VolleyLog.d(TAG, "Error: " + error.getMessage());
               hideProgressDialog();
         }
          @Override
          public Priority getPriority() {
                return priority;
          }
};

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.