Volley Network Image Loader

Hi All,

Volley is a library that handles the processing and caching of network requests. It helps to download the imaged from web asynchronously. We do not worry  about the Async Task to download the image from network because Volley library now can able to handle the image download asynchronously.

We already had known the famous library Universal Image Loder and Piccaso. Both are easy to handle to download the image in a thread pool and maintained the cache management.

Volley simplify everything and increases the app performances. - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
 Volley have lot of advantages:






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
    • Automatic scheduling of network requests.
    • Multiple concurrent network connections.
    • Transparent disk and memory response caching
    • Support for request prioritization.
    • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
    • Ease of customization, for example, for retry and backoff.
    • Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
    • Debugging and tracing tools.
    • Application performance
    There are two available cache implementations. The recommended approach uses a basic in memory LRU cache. For the disk cache implementation I chose to use the DiskLruCache written by Jake Wharton. I chose this implementation because it is frequently used in the Android community and represents a common use case for someone trying to retrofit their application for Volley. Using a disk based L1 cache may cause i/o blocking issues. Volley already has an implicit disk L2 cache. The disk L1 cache is included because I was originally unaware of how Volley handled image request caching. 

    For download or clone of Volley library you have to run predefined command in your system, In your system should have installed the git.

    1. git clone https://android.googlesource.com/platform/frameworks/volley
    2. android update project -p .
    3. ant jar
    Once you done this commond you can get the volley clone library in your directory.
    Only thing you have to use the  NetworkImageView in place of ImageView. I have share code for GridView image loader with volley that manage the cache management for network processing.



      






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf






  • Efficient network management
  • Easy to use request managements
  • Disk and memory cache management
  • Easy to extend and customize to our needs
  • - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
    Volley simplify everything and increases the app performances. - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf
    Volley simplify everything and increases the app performances. - See more at: http://www.survivingwithandroid.com/2013/11/android-volley-tutorial-post-download.html#sthash.ATBAtGr2.dpuf

    activity_main.xml

    < RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="comsunil.volleygridexample.MainActivity" >
    
        <gridview android:columnwidth="90dp" 
       android:horizontalspacing="5dp" 
       android:id="@+id/gridView" 
       android:layout_gravity="center"
       android:layout_height="match_parent" 
       android:layout_width="match_parent" 
       android:numcolumns="auto_fit" android:padding="5dp"
       android:stretchmode="columnWidth" 
       android:verticalspacing="5dp"/>
    
    < /RelativeLayout>
    

    grid_image_item.xml

    < ?xml version="1.0" encoding="utf-8"?>
    
    <framelayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:android="http://schemas.android.com/apk/res/android">
    
       <com .android.volley.toolbox.networkimageview="" 
       android:id="@+id/networkImageView"
       android:layout_alignparentleft="true" 
      android:layout_alignparenttop="true" 
       android:layout_height="100dp" 
       android:layout_width="100dp" 
       android:scaletype="centerCrop">
    
    </framelayout>
    

    MainActivity.java

    package comsunil.volleygridexample;
    
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.GridView;
    import android.widget.ImageView;
    
    import com.android.volley.toolbox.ImageLoader;
    import com.android.volley.toolbox.NetworkImageView;
    
    public class MainActivity extends ActionBarActivity {
    
       ImageLoader mImageLoader;
       NetworkImageView mNetworkImageView;
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      
      mImageLoader = MyVolleySingleton.getInstance(this).getImageLoader();
    
            final GridView gridView = (GridView) findViewById(R.id.gridView);
            gridView.setAdapter(new MyImageAdapter());
    
            
     }
    
      static class ViewHolder {
             ImageView imageView;
         }
    
         class MyImageAdapter extends BaseAdapter {
    
             @Override
             public int getCount() {
                 return ImageUrlArray.IMAGES.length;
             }
    
             @Override
             public Object getItem(int position) {
                 return null;
             }
    
             @Override
             public long getItemId(int position) {
                 return position;
             }
    
             @Override
             public View getView(int position, View convertView, ViewGroup parent) {
    
                 View view = convertView;
                 final ViewHolder gridViewImageHolder;
    //             check to see if we have a view
                 if (view == null) {
                     view = getLayoutInflater().inflate(R.layout.grid_image_item, parent, false);
                     gridViewImageHolder = new ViewHolder();
                     gridViewImageHolder.imageView = (ImageView) view.findViewById(R.id.networkImageView);
                     view.setTag(gridViewImageHolder);
                 } else {
                     gridViewImageHolder = (ViewHolder) view.getTag();
                 }
    
                 mNetworkImageView = (NetworkImageView) gridViewImageHolder.imageView;
                 mNetworkImageView.setDefaultImageResId(R.drawable.no_image);
                 mNetworkImageView.setErrorImageResId(R.drawable.error);
                 mNetworkImageView.setAdjustViewBounds(true);
                 mNetworkImageView.setImageUrl(ImageUrlArray.IMAGES[position], mImageLoader);
    
                 return view;
             }
         }
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
     }
    
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
       return true;
      }
      return super.onOptionsItemSelected(item);
     }
    }
    
    

    MyVolleySingleton.java

    package comsunil.volleygridexample;
    
    import android.content.Context;
    
    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.toolbox.ImageLoader;
    import com.android.volley.toolbox.Volley;
    
    /**
     * copied from the official documentation
     */
    public class MyVolleySingleton {
    
        private static MyVolleySingleton mVolleyInstance;
        private RequestQueue mRequestQueue;
        private ImageLoader mImageLoader;
        private static Context mContext;
    
        private MyVolleySingleton(Context context) {
            mContext = context;
            mRequestQueue = getRequestQueue();
            mImageLoader = new ImageLoader(mRequestQueue,
                    new MyLruBitmapCache(MyLruBitmapCache.getCacheSize(context))
            );
        }
    
        public static synchronized MyVolleySingleton getInstance(Context context) {
            if (mVolleyInstance == null) {
                mVolleyInstance = new MyVolleySingleton(context);
            }
            return mVolleyInstance;
        }
    
        public RequestQueue getRequestQueue() {
            if (mRequestQueue == null) {
                // use the application context
                mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
            }
            return mRequestQueue;
        }
    
        public  void addToRequestQueue(Request req) {
            getRequestQueue().add(req);
        }
    
        public ImageLoader getImageLoader() {
            return mImageLoader;
        }
    }
    
    

    MyLruBitmapCache.java

    package comsunil.volleygridexample;
    
    import android.content.Context;
    import android.graphics.Bitmap;
    import android.support.v4.util.LruCache;
    import android.util.DisplayMetrics;
    
    import com.android.volley.toolbox.ImageLoader;
    
    /**
     * copied from official documentation
     */
    public class MyLruBitmapCache extends LruCache
            implements ImageLoader.ImageCache {
    
        public MyLruBitmapCache(int maxSize) {
            super(maxSize);
        }
    
        public MyLruBitmapCache(Context ctx) {
            this(getCacheSize(ctx));
        }
    
        @Override
        protected int sizeOf(String key, Bitmap value) {
            return value.getRowBytes() * value.getHeight();
        }
    
        @Override
        public Bitmap getBitmap(String url) {
            return get(url);
        }
    
        @Override
        public void putBitmap(String url, Bitmap bitmap) {
            put(url, bitmap);
        }
    
        // Returns a cache size equal to approximately three screens worth of images.
        public static int getCacheSize(Context ctx) {
            final DisplayMetrics displayMetrics = ctx.getResources().
                    getDisplayMetrics();
            final int screenWidth = displayMetrics.widthPixels;
            final int screenHeight = displayMetrics.heightPixels;
            // 4 bytes per pixel
            final int screenBytes = screenWidth * screenHeight * 4;
    
            return screenBytes * 3;
        }
    }
    

    For network operation I recommended to use this library instead of AsynTask.

    package com.sunil.volleynetworkoperation;
    
    import org.json.JSONObject;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.TextView;
    
    import com.android.volley.Request;
    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.JsonObjectRequest;
    import com.android.volley.toolbox.Volley;
    
    public class MainActivity extends Activity {
    
     private TextView txtDisplay;
     
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      txtDisplay = (TextView) findViewById(R.id.txtDisplay);
      
      RequestQueue queue = Volley.newRequestQueue(this);
      String url = "http://echo.jsontest.com/key/value/one/two";
      
      JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener() {
    
       @Override
       public void onResponse(JSONObject response) {
        // TODO Auto-generated method stub
        txtDisplay.setText("Response => "+response.toString());
        findViewById(R.id.progressBar1).setVisibility(View.GONE);
       }
      }, new Response.ErrorListener() {
    
       @Override
       public void onErrorResponse(VolleyError error) {
        // TODO Auto-generated method stub
        
       }
       
      
      })
      
      
      /*{       // if you have any key value request
          @Override
          protected Map getParams() 
          {  
                  Map  params = new HashMap();  
                  params.put("name", "sunil");  
                  params.put("domain", "http://sunil.info");
                   
                  return params;  
          }
      }*/;
      
      queue.add(jsObjRequest);
     }
    
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
      return true;
     }
    
     @Override
     public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      int id = item.getItemId();
      if (id == R.id.action_settings) {
       return true;
      }
      return super.onOptionsItemSelected(item);
     }
    }
    
    
    Here you can dwonload the source code VolleyGridview

    22 comments:

    1. Blazing Star softech team is known for the skills, made for creativity and innovation and provides the best software solution ever.


      Software Development Company in Lucknow
      Web Development Company in Lucknow
      Software Company in Lucknow

      ReplyDelete
      Replies
      1. Android Chat Head Library
        Chat head is new feature which floats on screen instead of residing inside conventional application. This feature is very continent for multitasking as user can work and chat at the same time.
        Android Chat Head Library

        Delete
    2. where do i can download full instalation file of android sdk ?

      ReplyDelete
    3. It was really a nice article and i was really impressed by reading this article We are also giving all software Course Online Training.The android Online Training is one of the leading Online Training institute in the world.

      ReplyDelete
    4. This has been a vital weblog site page in reality. I've procured a great deal of data from your material. Much obliged to you for alluding to such proper point with us. I truly like all the incredible elements you offer. Much appreciated again and keeps it impending


      Website Design Agency in Bangalore | Website Development Companies Bangalore

      ReplyDelete
    5. win money online https://trafficmonsoon.com/?ref=luisdgd09

      ReplyDelete
    6. your download link is die. please re upload

      ReplyDelete
    7. Thank you for sharing this information.I have gone through your blog and its very wonderful Android training in Chennai

      ReplyDelete
    8. Thanks for a great information in your blog.I have read all the post of your blog.Great work on Android

      ReplyDelete
    9. Thanks for a great information in your blog.I have read all the post of your blog.Great work on Android

      ReplyDelete
    10. hai sunil ur link downlad source example dead..
      please fix url

      ReplyDelete
    11. hai sunil ur link downlad source example dead..
      please fix url

      ReplyDelete
    12. Thanks for the useful information.Your blog is really informative.
      The freeware version of Web app that comes with monitoring status of server and worldwide locations.
      https://play.google.com/store/apps/details?id=com.webapps.webapps

      ReplyDelete
    13. Great post!

      Useful information worthy of thanks ,

      http://ixgram.com

      ReplyDelete
    14. This blog provides useful information about new techniques and concepts.very impressive lines are given which is very attractive.
      java training in chennai

      ReplyDelete
    15. If you are develeloper and you want to develope any software and you don't have time then don't have time? Don't worry Sourcecodeguru provide you Readymade Sourcecodes for that.
      Sourcecodes like Amazing app, because we need such types of apps and ecommerce wordpress themes for mobile and laptops !

      ReplyDelete
    16. but in case of offline mode how to get images from cache..how to do

      ReplyDelete
    17. Together with it, iphone app development solution and android app developer become hot trends of software outsourcing companies. Special, software companies that target to global market like US or AU.

      ReplyDelete

    Debug Database in Android

    In my last tutorial, we have learned how we can use persistence database in android. We also understood which database wrapper we can use...

    Contact Me

    Name

    Email *

    Message *