Android Vollely library example

Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code.its very easy and faster.

how volley helps your application.? this are the benefits of volley

  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • 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.

So let’s Start build our application …!

App screen shot:

  • Create a Project I named it Volley_example.
  • Now quickly create two packages named app and helper.
  • Create your colour xml file in values => colour.xml 
 <?xml version="1.0" encoding="utf-8"?>  
 <resources>  
  <color name="list_divider">#dedede</color>  
   <color name="white">#ffffff</color>  
   <color name="lbl_product_name">#333333</color>  
   <color name="lbl_product_description">#444444</color>  
   <color name="bg_msg_you">#5eb964</color>  
   <color name="bg_msg_from">#e5e7eb</color>  
   <color name="msg_border_color">#a1a1a1</color>  
   <color name="bg_btn_join">#1e6258</color>  
   <color name="bg_msg_input">#e8e8e8</color>  
   <color name="text_msg_input">#626262</color>  
   <color name="lblFromName">#777777</color>  
 </resources>  
      • This step is very important one .here we going add the volley dependancy in  build.gradle

go to

 build.gradle

      then add a dependency

compile ‘com.mcxiaoke.volley:library-aar:1.0.0’.

      then press

SyncNow

    Button (top right corner) .
 dependencies {  
   compile fileTree(dir: 'libs', include: ['*.jar'])  
   compile 'com.android.support:appcompat-v7:23.0.0'  
   compile 'com.mcxiaoke.volley:library-aar:1.0.0'  
 }  

 

  •  Under utils package, create a class named LruBitmapCache.java and paste the below code. This class is required to handle image cache.

 

 package utils;  
 import android.graphics.Bitmap;  
 import android.support.v4.util.LruCache;  
 import com.android.volley.toolbox.ImageLoader;  
 /**  
  * Created by dhanish on 2/4/2016.  
  */  
 public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {  
   public static int getDefaultLruCacheSize() {  
     final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);  
     final int cacheSize = maxMemory / 8;  
     return cacheSize;  
   }  
   public LruBitmapCache() {  
     this(getDefaultLruCacheSize());  
   }  
   public LruBitmapCache(int sizeInKiloBytes) {  
     super(sizeInKiloBytes);  
   }  
   @Override  
   protected int sizeOf(String key, Bitmap value) {  
     return value.getRowBytes() * value.getHeight() / 1024;  
   }  
   @Override  
   public Bitmap getBitmap(String url) {  
     return get(url);  
   }  
   @Override  
   public void putBitmap(String url, Bitmap bitmap) {  
     put(url, bitmap);  
   }  
 }  
  • Crete a class named AppController.java under app package. This is a singleton class that extends from Application which will be executed on app launch. All the initialization of volley objects will be done here.
 package info.androidhive.palpalclient.app;  
 import info.androidhive.palpalclient.helper.LruBitmapCache;  
 import android.app.Application;  
 import android.text.TextUtils;  
 import com.android.volley.Request;  
 import com.android.volley.RequestQueue;  
 import com.android.volley.toolbox.ImageLoader;  
 import com.android.volley.toolbox.Volley;  
 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);  
     }  
   }  
 }  
    • Now open AndroidManifest.xml and add this AppController  class in  <application> tag using android:name property to execute the class automatically whenever app launches. Also add INTERNET permission . check the following example
 <?xml version="1.0" encoding="utf-8"?>  
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
   package="com.example.dhanish.volley_example" >  
   <uses-permission android:name="android.permission.INTERNET" />  
   <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />  
   <application  
     android:name=".AppController"  
     android:allowBackup="true"  
     android:icon="@mipmap/ic_launcher"  
     android:label="@string/app_name"  
     android:theme="@style/AppTheme" >  
     <activity  
       android:name=".MainActivity"  
       android:label="@string/app_name" >  
       <intent-filter>  
         <action android:name="android.intent.action.MAIN" />  
         <category android:name="android.intent.category.LAUNCHER" />  
       </intent-filter>  
     </activity>  
   </application>  
 </manifest>  
    • Create your custom  list view. copy paste following code in your layout folder
      Create a List view activity

 layout => 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"  
   tools:context=".MainActivity">  
   <ListView  
     android:id="@+id/list"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:paddingBottom="25dp"  
     android:divider="@color/list_divider"  
     android:dividerHeight="1dp">  
   </ListView>  
 </RelativeLayout>  
    Create a Custom list view layout

layout => product_list.xml

 <?xml version="1.0" encoding="utf-8"?>  
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="match_parent"  
   android:layout_height="match_parent"  
   android:orientation="vertical">  
   <com.android.volley.toolbox.NetworkImageView  
     android:id="@+id/productImage"  
     android:layout_width="100dp"  
     android:layout_height="wrap_content"  
     android:layout_alignBottom="@+id/productDescription"  
     android:layout_alignParentLeft="true"  
     android:layout_alignParentTop="true"  
     android:layout_marginLeft="5dp"  
     android:layout_marginRight="1dp"  
     android:layout_marginTop="8dp"  
     android:scaleType="fitStart"></com.android.volley.toolbox.NetworkImageView>  
   <TextView  
     android:id="@+id/productName"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_alignParentTop="true"  
     android:layout_alignStart="@+id/productDescription"  
     android:layout_marginLeft="8dp"  
     android:layout_marginTop="21dp"  
     android:layout_toStartOf="@+id/btnAddToCart"  
     android:padding="5dp"  
     android:text="abc"  
     android:textColor="@color/lbl_product_name"  
     android:textSize="16dp"  
     android:textStyle="bold" />  
   <TextView  
     android:id="@+id/productDescription"  
     android:layout_width="180dp"  
     android:layout_height="wrap_content"  
     android:layout_below="@+id/btnAddToCart"  
     android:layout_marginLeft="12dp"  
     android:layout_toStartOf="@+id/btnAddToCart"  
     android:padding="5dp"  
     android:text="abc"  
     android:textColor="@color/lbl_product_description" />  
   <TextView  
     android:id="@+id/productPrice"  
     android:layout_width="fill_parent"  
     android:layout_height="wrap_content"  
     android:layout_alignEnd="@+id/btnAddToCart"  
     android:layout_alignTop="@+id/productDescription"  
     android:layout_marginLeft="0dp"  
     android:layout_toEndOf="@+id/productName"  
     android:padding="5dp"  
     android:text="abac"  
     android:textColor="@color/lbl_product_description" />  
   <Button  
     android:id="@+id/btnAddToCart"  
     android:layout_width="wrap_content"  
     android:layout_height="30dp"  
     android:layout_alignParentEnd="true"  
     android:layout_alignTop="@+id/productName"  
     android:layout_marginLeft="5dp"  
     android:layout_marginRight="5dp"  
     android:background="#4c1a30"  
     android:paddingLeft="5dp"  
     android:paddingRight="5dp"  
     android:text="Add"  
     android:textColor="@color/white" />  
 </RelativeLayout>  
    • Create your Product Model class. Product 
 package com.example.dhanish.volley_example;  
 import java.math.BigDecimal;  
 /**  
  * Created by dhanish on 2/7/2016.  
  */  
 public class Product {  
   String name;  
   String descr;  
   Double price;  
   String img;  
   int sku;  
   public Product(String name, String descr, Double price, String img, int sku) {  
     this.name = name;  
     this.descr = descr;  
     this.price = price;  
     this.img = img;  
     this.sku = sku;  
   }  
   public Product() {  
   }  
   public String getName() {  
     return name;  
   }  
   public void setName(String name) {  
     this.name = name;  
   }  
   public String getDescr() {  
     return descr;  
   }  
   public void setDescr(String descr) {  
     this.descr = descr;  
   }  
   public Double getPrice() {  
     return price;  
   }  
   public void setPrice(Double price) {  
     this.price = price;  
   }  
   public String getImg() {  
     return img;  
   }  
   public void setImg(String img) {  
     this.img = img;  
   }  
   public int getSku() {  
     return sku;  
   }  
   public void setSku(int sku) {  
     this.sku = sku;  
   }  
 }  
    • Create a Adapter class for your Custom list view .we done this before in Custom list view tutorial create a class ListProductAdapter. 
 package com.example.dhanish.volley_example;  
 import android.app.Activity;  
 import android.content.Context;  
 import android.view.LayoutInflater;  
 import android.view.View;  
 import android.view.ViewGroup;  
 import android.widget.BaseAdapter;  
 import android.widget.Button;  
 import android.widget.TextView;  
 import com.android.volley.toolbox.ImageLoader;  
 import com.android.volley.toolbox.NetworkImageView;  
 import java.util.List;  
 /**  
  * Created by dhanish on 2/7/2016.  
  */  
 public class ListProductAdapter extends BaseAdapter {  
   private Activity activity;  
   private LayoutInflater inflater;  
   private List<Product> products;  
   private ListProductAdapterListener listener;  
   ImageLoader imageLoader = AppController.getInstance().getImageLoader();  
   public ListProductAdapter(Activity activity, List<Product> feedItems,ListProductAdapterListener listener) {  
     this.activity = activity;  
     this.products = feedItems;  
     this.listener = listener;  
   }  
   @Override  
   public int getCount() {  
     return products.size();  
   }  
   @Override  
   public Object getItem(int position) {  
     return products.get(position);  
   }  
   @Override  
   public long getItemId(int position) {  
     return position;  
   }  
   @Override  
   public View getView(int position, View convertView, ViewGroup parent) {  
     if (inflater == null)  
     inflater = (LayoutInflater) activity  
         .getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
     if (convertView == null)  
       convertView = inflater.inflate(R.layout.product_list, null);  
     if (imageLoader == null)  
       imageLoader = AppController.getInstance().getImageLoader();  
     TextView name = (TextView) convertView.findViewById(R.id.productName);  
     TextView description = (TextView) convertView  
         .findViewById(R.id.productDescription);  
     TextView price = (TextView) convertView.findViewById(R.id.productPrice);  
     NetworkImageView image = (NetworkImageView) convertView  
         .findViewById(R.id.productImage);  
     Button btnAddToCart = (Button) convertView  
         .findViewById(R.id.btnAddToCart);  
     final Product product = products.get(position);  
     name.setText(product.getName());  
     description.setText(product.getDescr());  
     price.setText("Price: $" + product.getPrice());  
     // user profile pic  
     image.setImageUrl(product.getImg(), imageLoader);  
     btnAddToCart.setOnClickListener(new View.OnClickListener() {  
       @Override  
       public void onClick(View v) {  
         listener.onAddToCartPressed(product);  
       }  
     });  
     return convertView;  
   }  
   public interface ListProductAdapterListener {  
     public void onAddToCartPressed(Product product);  
   }  
 }  

Making JSON request

    This is our final stage of application .this section explain how to make network calls using JSON.
      Volley provides an easy to make json requests. If you are expecting json object in the response, you should use

JsonObjectRequest

      class or if the response is json array,

JsonArrayRequest

      class  and if it’s a JSON String use

JsonSting

    class should be used.
      following example of

JSON Object Request ,JSON Array Request

      and

JSON String

JSON Object Request

1:  // Tag used to cancel the request  
2:  String tag_json_obj = "json_obj_req";  
3:  String url = "here your json URL";  
6: 
7:      JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,  
8:          url, null,  
9:          new Response.Listener<JSONObject>() {  
10:            @Override  
11:            public void onResponse(JSONObject response) {  
12:              Log.d(TAG, response.toString());  
13:          
14:            }  
15:          }, new Response.ErrorListener() {  
16:            @Override  
17:            public void onErrorResponse(VolleyError error) {  
18:              VolleyLog.d(TAG, "Error: " + error.getMessage());  
19:            
21:            }  
22:          });  
23:  // Adding request to request queue  
24:  AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);  
      Volley mostly works with just two classes,

RequestQueue (

      in line 24 of above program) and

Request

      . You first create a

RequestQueue

    , which manages worker threads and delivers the parsed results back to the main thread. You then pass it one or more Request objects.

JSON ARRAY Request

1:  String tag_json_arry = "json_array_req";  
2:  String url = "JSON URL here";  
3:   
6:  JsonArrayRequest req = new JsonArrayRequest(url,  
7:          new Response.Listener<JSONArray>() {  
8:            @Override  
9:            public void onResponse(JSONArray response) {  
10:              Log.d(TAG, response.toString());      
11:                    
12:            }  
13:          }, new Response.ErrorListener() {  
14:            @Override  
15:            public void onErrorResponse(VolleyError error) {  
16:              VolleyLog.d(TAG, "Error: " + error.getMessage());  
17:              
18:            }  
19:          });  
20:  // Adding request to request queue  
21:  AppController.getInstance().addToRequestQueue(req, tag_json_arry);  

JSON String Request

1
2:  String tag_string_req = "string_req";  
3:  String url = "here is json string";  
4    
7  StringRequest strReq = new StringRequest(Method.GET,  
8:          url, new Response.Listener<String>() {  
9:            @Override  
10:            public void onResponse(String response) {  
11:              Log.d(TAG, response.toString());  
12:          
13:            }  
14:          }, new Response.ErrorListener() {  
15:            @Override  
16:            public void onErrorResponse(VolleyError error) {  
17:              VolleyLog.d(TAG, "Error: " + error.getMessage());  
18:             
19:            }  
20:          });  
21:  // Adding request to request queue  
22:  AppController.getInstance().addToRequestQueue(strReq, tag_string_req);  

this are the way we make JSON request in volley . let’s continue our project …!

      • Create your main class for marking json request  MainActivity

my JSON URL is ”

http://dhanishpk.com/sample/getdata.php

    ” . just try this url in your browser you can see the structure of JSON array..
 package com.example.dhanish.volley_example;  
 import android.app.ProgressDialog;  
 import android.nfc.Tag;  
 import android.support.v7.app.AppCompatActivity;  
 import android.os.Bundle;  
 import android.util.Log;  
 import android.view.Menu;  
 import android.view.MenuItem;  
 import android.widget.Button;  
 import android.widget.ListView;  
 import android.widget.Toast;  
 import com.android.volley.Request;  
 import com.android.volley.Response;  
 import com.android.volley.VolleyError;  
 import com.android.volley.VolleyLog;  
 import com.android.volley.toolbox.JsonArrayRequest;  
 import com.android.volley.toolbox.StringRequest;  
 import org.json.JSONArray;  
 import org.json.JSONException;  
 import org.json.JSONObject;  
 import java.math.BigDecimal;  
 import java.util.ArrayList;  
 import java.util.List;  
 public class MainActivity extends AppCompatActivity implements ListProductAdapter.ListProductAdapterListener {  
   private ListView listView;  
   private Button btnCheckout;  
   private ProgressDialog pDialog;  
   private ListProductAdapter adapter;  
   private List<Product> productsList;  
   @Override  
   protected void onCreate(Bundle savedInstanceState) {  
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.activity_main);  
     listView = (ListView) findViewById(R.id.list);  
     productsList = new ArrayList<Product>();  
     adapter = new ListProductAdapter(this, productsList, (ListProductAdapter.ListProductAdapterListener) this);  
     listView.setAdapter(adapter);  
     pDialog = new ProgressDialog(this);  
     pDialog.setCancelable(false);  
     fetchProducts();  
   }  
   private void showpDialog() {  
     if (!pDialog.isShowing())  
       pDialog.show();  
   }  
   private void hidepDialog() {  
     if (pDialog.isShowing())  
       pDialog.dismiss();  
   }  
   private void fetchProducts() {  
     pDialog.setMessage("Fetching products...");  
     Log.i("fec", "f");  
     showpDialog();  
     Log.i("show dialog", "dilaog on");  
     // Making json object request  
     JsonArrayRequest strReq = new JsonArrayRequest("http://dhanishpk.com/sample/getdata.php", new Response.Listener<JSONArray>() {  
       @Override  
       public void onResponse(JSONArray response) {  
         for (int i = 0; i < response.length(); i++) {  
           try {  
             JSONObject obj = response.getJSONObject(i);  
             String name = obj.getString("name");  
             Double price = obj.getDouble("price");  
             String desc = obj.getString("description");  
             String img=obj.getString("image");  
             Product p = new Product();  
             p.setName(name);  
             p.setPrice(price);  
             p.setDescr(desc);  
             p.setImg("http://dhanishpk.com/sample/"+img);  
             productsList.add(p);  
             adapter.notifyDataSetChanged();  
           } catch (JSONException e) {  
             e.printStackTrace();  
           }  
         }  
         hidepDialog();  
       }  
     }, new Response.ErrorListener() {  
       @Override  
       public void onErrorResponse(VolleyError volleyError) {  
         pDialog.hide();  
       }  
     });  
     AppController.getInstance().addToRequestQueue(strReq);  
   }  
   @Override  
   public boolean onCreateOptionsMenu(Menu menu) {  
     // Inflate the menu; this adds items to the action bar if it is present.  
     getMenuInflater().inflate(R.menu.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();  
     //noinspection SimplifiableIfStatement  
     if (id == R.id.action_settings) {  
       return true;  
     }  
     return super.onOptionsItemSelected(item);  
   }  
   @Override  
   public void onAddToCartPressed(Product product) {  
 Toast.makeText(getApplicationContext(),"Item add to Cart: "+product.getName(),Toast.LENGTH_LONG).show();  
   }  
 }  

final application will be look like this

Download Source Code here: Click here

Reply

eleven + sixteen =