Android Volley Tutorial With Example

This is android volley tutorial. Here you will learn about android volley library and how to use it.

What is Volley?

Volley is a network library that helps in doing network related operations like fetching image or data.

Here are some features of this library.

  • Supports request queuing and prioritization
  • Effective cache management
  • Multiple concurrent network connections can be established
  • Supports request cancelling
  • No need to use asynctask as it performs all network operations asynchronously.

Android Volley Tutorial 1

Android Volley Tutorial

Using volley we can fetch simple string, image or json data. Below I have given example for each of them.

First we create a request; it can be string, image or json. Then create a request queue and finally add the request in the request queue.

 

Pre-requisites

1. Add volley support in build.gradle by adding following line under dependencies section.  After adding just sync the project.

compile 'com.android.volley:volley:1.0.0'

2. Add internet access permission in AndroidManifest.xml file.

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

 

Fetching String Data

StringRequest class is used to create a string request. We specify the URL and then receive the string in response. Below example shows how to do this.

Create an android project with package name com.androidvolleyexample and add following code in respective files.

activity_main.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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:id="@+id/txt"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Fetch Data"/>

</LinearLayout>

 

MainActivity.xml

package com.androidvolleyexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
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.StringRequest;
import com.android.volley.toolbox.Volley;


public class MainActivity extends Activity {
    TextView txt;
    Button btn;
    String url ="http://thecrazyprogrammer.com/wp-content/uploads/demo.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt = (TextView)findViewById(R.id.txt);
        btn = (Button)findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
                    @Override
                    public void onResponse(String s) {
                        txt.setText(s);
                    }
                },new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        txt.setText("Some error occurred!!");
                    }
                });

                RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
                rQueue.add(request);
            }
        });
    }
}

 

Screenshot

Android Volley Tutorial 3

 

Fetching Image

ImageRequest class is used to create an image request. We specify the URL and then receive the bitmap in response. Below example shows how to do this.

Create an android project with package name com.androidvolleyexample and add following code in respective files.

activity_main.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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp"
        android:id="@+id/img"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Fetch Data"/>

</LinearLayout>

 

MainActivity.xml

package com.androidvolleyexample;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;


public class MainActivity extends Activity {
    ImageView img;
    Button btn;
    String url ="http://thecrazyprogrammer.com/wp-content/uploads/2015/07/The-Crazy-Programmer.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        img = (ImageView)findViewById(R.id.img);
        btn = (Button)findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>(){
                    @Override
                    public void onResponse(Bitmap b) {
                        img.setImageBitmap(b);
                    }
                }, 0, 0, null,

                new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Toast.makeText(MainActivity.this, "Some error occurred!!", Toast.LENGTH_LONG).show();
                    }
                });

                RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
                rQueue.add(request);
            }
        });
    }
}

 

Screenshot

Android Volley Tutorial 2

 

Fetching JSON Data

JsonObjectRequest and JsonArrayRequest class is used to create a json request. We specify the URL and then receive the json data in response. Same as string and image fetched above, we can fetch json data. So I am not giving its example as you can easily do yourself.

 

Sending Data

For sending some data we have to use post request and override getParams() method. The data is sent in key value pairs. It can be done in following way.

MainActivity.java

package com.androidvolleyexample;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
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;
import com.android.volley.toolbox.Volley;

import java.util.HashMap;
import java.util.Map;


public class MainActivity extends Activity {
    TextView txt;
    Button btn;
    String url ="http://192.168.1.8/JavaRESTfullWS/DemoService";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt = (TextView)findViewById(R.id.txt);
        btn = (Button)findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>(){
                    @Override
                    public void onResponse(String s) {
                        txt.setText(s);
                    }
                },new Response.ErrorListener(){
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        txt.setText("Some error occurred!!");
                    }
                })
                {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> parameters = new HashMap<String, String>();
                        parameters.put("message", "Hello");
                        return parameters;
                    }
                };

                RequestQueue rQueue = Volley.newRequestQueue(MainActivity.this);
                rQueue.add(request);
            }
        });
    }
}

 

Comment below if you found anything incorrect or have doubts related to above android volley tutorial.

7 thoughts on “Android Volley Tutorial With Example”

  1. Hi sir
    your tutorial was great, thanks alot.
    I’m new in android, i don’t know the role of this code snippet:

    @Override
    protected Map getParams() throws AuthFailureError {
    Map parameters = new HashMap();
    parameters.put(“message”, “Hello”);
    return parameters;

    Is there any tutorial or if u could explain more I will appriciate

Leave a Comment

Your email address will not be published. Required fields are marked *