My Life with Android
Introduction Android Componets UserInterface Advanced UI Data Storage Advanced Concepts Others New Studio

An Introduction to Volley

At Google I/O, Google debuted the new, hip way to make network requests within an Android application by introducing the world to the Volley Networking Library.

Volley is a networking library that manages network requests and their response caches without the developer having to write a lot of code.It makes networking for Android apps easier and most importantly, faster.

It manages the processing and caching of network requests and it saves developers valuable time from writing the same network call/cache code again and again.

Volley is an android library released by Google that can be used to handle Android HTTP request and response.

Why use Volley?

Well we may ask why we need to use another library if we have already everything we need to handle network connection (i.e Http connection). Well, if you read the previous posts, we have noticed we have some work to do: for example we have to create an AsyncTask, handle the network connection erorrs and so on. Volley simplify everything and increases the app performances.

Features of Volley library

a) Automatically schedules the network requests.
b) Supports request prioritization. This means that you can load content depending of priorities, for example the main content could have a high priority, but the images a low priority.
c) Provides transparent disk and memory cache that allows for quick reloading of data. Transparent cache means that the caller doesn't have to know about the existence of the cache. That is, the cache is implemented automatically. You do, however, have the possibility to disable the caching.
d) Provides a good API for canceling requests. You can cancel a single request, or cancel requests depending on some filters.

Volley - StringRequest

Example 1

RequestQueue care of queuing the requests and handle the responses.
Request is the base class for creating network requests (GET, POST).
Listener is a callback interface for delivering the result, and
ErrorListener is a callback interface for delivering error responses.
Step 1: VolleySingleton.java
Step 2: Add internet permission
Step 3: Create an instance of RequestQueue
Step 4: Create the request
Step 6: Execute the request
Step 1: VolleySingleton.java
package com.practice.android_samples;

import android.app.Application;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class VolleySingleton extends Application{
	private static VolleySingleton mInstance;

	
	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = this;
	}

	public static synchronized VolleySingleton getInstance() {
		return mInstance;
	}
	public RequestQueue getRequestQueue() {
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
		}
		return mRequestQueue;
	}
	
}


Step 2: Two request(String,Json)
package com.practice.android_samples;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
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.StringRequest;

public class VolleyExample extends Activity {
	TextView textView1;
	RequestQueue queue;
	Button btnClear;
	String DETAIL_URL = "http://bytecodetechnosolutions.com/Testing/testing.php";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_volley_res);

		btnClear=(Button)findViewById(R.id.btnClear);
		textView1=(TextView)findViewById(R.id.textView1);

		Cache cache = VolleySingleton.getInstance().getRequestQueue().getCache();
		Entry entry = cache.get(DETAIL_URL);
		if (entry != null) {
			// fetch the data from cache
			try {
				String data = new String(entry.data, "UTF-8");
				textView1.setText(data);
			}catch(Exception e){}
		}

		MakeStringValleyServerRequest(DETAIL_URL);

		btnClear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				queue.getCache().clear();
			}
		});
	}
	private RequestQueue mRequestQueue;
	private void MakeStringValleyServerRequest(String url){
queue = VolleySingleton.getInstance().getRequestQueue();
		StringRequest jsObjRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>(){
			@Override
			public void onResponse(String arg0) {
				textView1.setText(arg0);
			}},new Response.ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError arg0) {
					textView1.setText("Error");
				}
			});
		//jsObjRequest.setShouldCache(true);
		queue.add(jsObjRequest);
	}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>

Volley - JsonObject Request

Example 1

RequestQueue care of queuing the requests and handle the responses.
Request is the base class for creating network requests (GET, POST).
Listener is a callback interface for delivering the result, and
ErrorListener is a callback interface for delivering error responses.
Step 1: VolleySingleton.java
Step 2: Add internet permission
Step 3: Create an instance of RequestQueue
Step 4: Create the request
Step 6: Execute the request
Step 1: VolleySingleton.java
package com.practice.android_samples;

import android.app.Application;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class VolleySingleton extends Application{
	private static VolleySingleton mInstance;
	private RequestQueue mRequestQueue;
	
	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = this;
	}

	public static synchronized VolleySingleton getInstance() {
		return mInstance;
	}
	public RequestQueue getRequestQueue() {
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
		}
		return mRequestQueue;
	}
	
}


Step 2: Two request(String,Json)
package com.practice.android_samples;

import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
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;

public class VolleyExample extends Activity {
	TextView textView1;
	RequestQueue queue;
	Button btnClear;
	String DETAIL_URL = "http://bytecodetechnosolutions.com/CPIMT/APIs/v1/geYoutubePlayList.php";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_volley_res);

		btnClear=(Button)findViewById(R.id.btnClear);
		textView1=(TextView)findViewById(R.id.textView1);

		queue = VolleySingleton.getInstance().getRequestQueue();

		Cache cache = VolleySingleton.getInstance().getRequestQueue().getCache();
		Entry entry = cache.get(DETAIL_URL);
		if (entry != null) {
			// fetch the data from cache
			try {
				String data = new String(entry.data, "UTF-8");
				textView1.setText(data);
			}catch(Exception e){}
		}

		MakeValleyServerRequest(DETAIL_URL);

		btnClear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				queue.getCache().clear();
			}
		});
	}

	private void MakeValleyServerRequest(String url){
			JsonObjectRequest jsObjRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
				@Override
				public void onResponse(JSONObject response) {
					textView1.setText(response.toString());
				}
			}, new Response.ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError error) {
					textView1.setText("Error");
				}
			});
			queue.add(jsObjRequest);

		}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>

Introduction

In every Android application, you have to use the findViewById() method for each view in the layout that you want to use in your application's code. But as applications' designs get more complex layouts, the call to this method becomes repetitive and this is where the Butter Knife library comes in.

The Butter Knife library, developer and maintained by Jake Wharton (Square Inc.), has annotations that help developers to instantiate the views from our activity or fragment. It also has annotations to handle events like onClick(), onLongClick(), etc.

1. Using the Butter Knife Library

Step 1: Add the Dependency
Add the following dependency to the project's build.gradle file:

compile 'com.jakewharton:butterknife:7.0.1'

Next, synchronize your project with this file by pressing the synchronize button.

Step 2: Use the Annotations
In every activity or fragment, you have to remove, or comment out, every call of the findViewById() method and add the @InjectView annotation before the declaration of the variable, indicating the identifier of the view.
  @Bind(R.id.title) TextView title;
  @Bind(R.id.subtitle) TextView subtitle;
Step 3: Inject Views
ButterKnife.inject(this);
Example :
class ExampleActivity extends Activity {
  @Bind(R.id.title) TextView title;
  @Bind(R.id.subtitle) TextView subtitle;
  @Bind(R.id.footer) TextView footer;

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.simple_activity);
    ButterKnife.bind(this);
    // TODO Use fields...
  }
}
If you are using fragments, you have to specify the source of the views in the onCreateView() method as shown below.
View view = inflater.inflate(R.layout.sample_fragment, null);
ButterKnife.inject(this, view);
LISTENER BINDING
Listeners can also automatically be configured onto methods.
@OnClick(R.id.submit)
public void submit(View view) {
  // TODO submit data to server...
}
Define a specific type and it will automatically be cast.
@OnClick(R.id.submit)
public void sayHi(Button button) {
  button.setText("Hello!");
}
You can now start using the views in your application's code. Butter Knife will handle the instantiation of every single view for you. Here Reference

Using the Butter Knife Library with List Views

The ListView class is a special case to implement, because you instantiate the views inside an adapter. To integrate the Butter Knife library in a list view, you first have to create the custom layout for the items in the list view. I'm going to name mine list_view_item and add the following layout:
<?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:padding="10dp"
    android:background="@android:color/white">
    <ImageView
        android:id="@+id/image_in_item"
        android:layout_width="100dp"
        android:layout_height="100dp"/>
    <TextView
        android:id="@+id/textview_in_item"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="16sp"
        android:layout_toRightOf="@+id/image_in_item"
        android:layout_marginLeft="10dp"/>
</RelativeLayout>
In this simple layout, we&39#;re going to show an image and some text. Next, we need to create the adapter for the list view. Let&39#;s name it ListViewAdapter.
public class ListViewAdapter extends BaseAdapter {
 
    LayoutInflater inflater;
 
    public ListViewAdapter(LayoutInflater inflater){
        this.inflater = inflater;
    }
 
    @Override
    public int getCount() {
        return 5;
    }
 
    @Override
    public Object getItem(int position) {
        return null;
    }
 
    @Override
    public long getItemId(int position) {
        return 0;
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return null;
    }
 
    static class ViewHolder{
 
        public ViewHolder(View view){
             
        }
    }
}
Inside the adapter class, there's a static class called ViewHolder to keep it in order. We're going to use this class to contain the views. Let's implement the ViewHolder class as follows:
static class ViewHolder{
    @InjectView(R.id.image_in_item)
    ImageView image;
    @InjectView(R.id.textview_in_item)
    TextView text;
 
    public ViewHolder(View view){
        ButterKnife.inject(this, view);
    }
}
All we have to do now is modify the getView() method as follows:
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
 
    View view = inflater.inflate(R.layout.list_view_item, parent, false);
    holder = new ViewHolder(view);
 
    Picasso.with(inflater.getContext())
        .load("http://youtube.com/200/200/sports/" + (position+1))
        .into(holder.image);
 
    holder.text.setText("This is a text for the image number: "+position);
 
    return view;
}
Finally, all you have to do is to instantiate the list view and attach the adapter. I'm going to do this inside a new activity, ListViewActivity, as shown below. You can see an example of this implementation in the source files of this tutorial.
public class ListViewActivity extends ActionBarActivity {
 
    @InjectView(R.id.listView)
    ListView list;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_view);
 
        ButterKnife.inject(this);
 
        list.setAdapter(new ListViewAdapter((LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE)));
    }
}

Introduction

Official Picasso Lib

Introduction

In the passed Google Developer Summit Thailand, Google introduced us an Image Loader Library for Android developed by bumptech named Glide as a library that recommended by Google. It has been used in many Google open source projects till now including Google I/O 2014 official application.

Import to project

Both Picasso and Glide are on jcenter. You can simply import it to your project with dependency like this:
Picasso
dependencies {
    compile 'com.squareup.picasso:picasso:2.5.1'
}
Glide
dependencies {
    compile 'com.github.bumptech.glide:glide:3.5.2'
    compile 'com.android.support:support-v4:22.0.0'
}
Anyway Glide also needs Android Support Library v4, please don't forget to import support-v4 to your project like above as well.

Basic
It is very similar to Picasso. The way to load an image to ImageView with Glide is quite the same as Picasso.
Picasso
Picasso.with(context)
    .load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
    .into(ivImg);
Glide
Glide.with(context)
    .load("http://inthecheesefactory.com/uploads/source/glidepicasso/cover.jpg")
    .into(ivImg);
Ref : Diff. b/w Glide and Picasso
Note to reader
We are not in any way associated with either Glide or Picasso - we're simply passionate Android developers sharing our results and experience with the two libraries.

Post Data to server using Volley Lib

Step 1: Add internet permission
Step 2: VolleySingleton.java
Step 3: MainActivity.java
Step 4: main_activity.xml
1. In Androidmanifeast.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.volleryregistration"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="9" />

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:name="com.example.volleryregistration.VolleySingleton"
        android:allowBackup="true"
        android:icon="@drawable/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>
2. VolleySingleton.java
import android.app.Application;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

public class VolleySingleton extends Application{
	private static VolleySingleton mInstance;
	private RequestQueue mRequestQueue;
	
	@Override
	public void onCreate() {
		super.onCreate();
		mInstance = this;
	}

	public static synchronized VolleySingleton getInstance() {
		return mInstance;
	}
	public RequestQueue getRequestQueue() {
		if (mRequestQueue == null) {
			mRequestQueue = Volley.newRequestQueue(getApplicationContext());
		}
		return mRequestQueue;
	}
}
3. MainActivity.java
import java.util.HashMap;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
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.StringRequest;

public class MainActivity extends Activity {
	EditText etName,etPhone;
	Button btnSubmit;
	RequestQueue queue;
	Button btnClear;
	String DETAIL_URL = "http://eduautomations.com/FoodOn/v1/testing.php";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		etName=(EditText)findViewById(R.id.etName);
		etPhone=(EditText)findViewById(R.id.etPhone);
		btnSubmit=(Button)findViewById(R.id.btnSubmit);
		btnSubmit.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				MakeStringValleyServerRequest(DETAIL_URL,etName.getText().toString(),etPhone.getText().toString());
			}
		});
		
	}
	private void MakeStringValleyServerRequest(String url,final String name,final String phono){
		queue = VolleySingleton.getInstance().getRequestQueue();
		StringRequest jsObjRequest=new StringRequest(Request.Method.POST, url, new Response.Listener<String>(){
			@Override
			public void onResponse(String response) {
				Toast.makeText(getApplicationContext(), ""+response, Toast.LENGTH_SHORT).show();
			}},new Response.ErrorListener() {
				@Override
				public void onErrorResponse(VolleyError error) {
					Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
				}
			}){
		     @Override
		       protected Map<String, String> getParams() {
		     Map<String, String> params = new HashMap<String, String>();
		     params.put("name",name);
		     params.put("phone",phono);

		     return params;
		 }
		  };
		//jsObjRequest.setShouldCache(true);
		queue.add(jsObjRequest);
	}
}

4. main_activity.xml
<LinearLayout 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:orientation="vertical" >

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/etPhone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="25dp"
        android:ems="10" >
    </EditText>

    <Button
        android:id="@+id/btnSubmit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="Submit" />

</LinearLayout>
RESULT

<?php

$name=$_POST["name"];
$phone=$_POST["phone"];

 $hostname = "localhost";
 $dbname = "eduautom_foodon";
 $username = "eduautom_foodon";
 $password = "foodon@123";
 $usertable = "tb_registration";

 $con=mysql_connect($hostname, $username, $password) OR DIE ("Unable to connect to database! Please try again later.");
 mysql_select_db($dbname);


 if(isset($_POST["name"])) {
 SignUp(); 
 }else{
echo 'empty';
}


function NewUser() {

$name=$_POST["name"];
$phone=$_POST["phone"];
$query = "INSERT INTO tb_registration(name,phone) VALUES ('$name','$phone')"; 
$data = mysql_query ($query)or die(mysql_error()); 
if($data) { 
      echo "YOUR REGISTRATION IS COMPLETED..."; 
    }else{
echo "Failed..."; 
} 
 } 


 function SignUp() { 
$name=$_POST["name"];
$phone=$_POST["phone"];
          $query = mysql_query("SELECT * FROM tb_registration WHERE name= '$name' AND phone= '$phone'");
	        if(!$row = mysql_fetch_array($query)){ 
				    NewUser(); 
	            } else { 
	                echo "SORRY...YOU ARE ALREADY REGISTERED USER..."; 
	            } 
 }

?>

Display JSON Array using Volley Lib

In main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Clear" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

</LinearLayout>
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Cache;
import com.android.volley.Cache.Entry;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;

public class VolleyArrayListEx extends Activity{
	TextView textView1;
	RequestQueue queue;
	Button btnClear;
	String DETAIL_URL = "http://bytecodetechnosolutions.com/Testing/listviewdata1.php";
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.volly_list_ex);
		btnClear=(Button)findViewById(R.id.btnClear);
		textView1=(TextView)findViewById(R.id.textView1);

		queue = VolleySingleton.getInstance().getRequestQueue();

		Cache cache = VolleySingleton.getInstance().getRequestQueue().getCache();
		Entry entry = cache.get(DETAIL_URL);
		if (entry != null) {
			// fetch the data from cache
			try {
				String data = new String(entry.data, "UTF-8");
				textView1.setText(data);
			}catch(Exception e){}
		}

		MakeVolleyServerRequest(DETAIL_URL);

		btnClear.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				queue.getCache().clear();
			}
		});
	}

	ProgressDialog pd;
	private void MakeVolleyServerRequest(String url){
		pd=new ProgressDialog(VolleyArrayListEx.this);
		pd.setMessage("Please wait,data is being loaded...");
		pd.show();
        JsonArrayRequest jreq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {

                    @Override
                    public void onResponse(JSONArray response) {
                 
                    	parseResponse(response);
                    	pd.dismiss();
                    	textView1.setText(res);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                    	pd.dismiss();
                    	textView1.setText("error");
                    }
                });
			
			queue.add(jreq);
		}
	String res="";
	ArrayList<HashMap<String, String>> alRes;
	private void parseResponse(JSONArray response){
		alRes=new ArrayList<HashMap<String, String>>();
		  for (int i = 0; i < response.length(); i++) {
              try {
                  JSONObject jo = response.getJSONObject(i);
                  String playlist_title = jo.getString("playlist_title");
                  HashMap<String, String> hm=new HashMap<String, String>();
                  hm.put("playlist_title", playlist_title);
                  alRes.add(hm);
                  res+="Title : "+playlist_title+"\n";
                  
              } catch (JSONException e) {
                  e.printStackTrace();
              }
          }
	}
	
}