Android Volley Library Tutorial
Volley is a networking library that manages network requests and their response caches without the developer having to write a lot of “boilerplate” code. Volley implements tools that allow for simultaneous requests to run on a pool of threads that can be given priority over one another. All of this is done, while implementing a transparent cache that allows for quick reloading of data. It is, however, not for everything. Responses are delivered whole in memory, so it is less than ideal for large downloads such as music and movies. It is alternatively geared towards smaller requests such as JSON files, images, and other files of that size and nature.
Some features of volley :
- Request queuing and prioritization
- Effective request cache and memory management
- Extensibility and customization of the library to our needs
- Cancelling the requests
You can take a look at this presentation before continuing to tutorial to understand volley more.
Preview
Lets get started
1. Adding volley.jar to your project
In Android Studio create a new project by navigating to File ⇒ New ⇒ Android Application Project and fill required details. Volley can be added to project as gradle dependency in app level build.gradle file.
1 2 3 4 |
dependencies { ... compile 'com.android.volley:volley:1.0.0' } |
2. Creating Volley Singleton class
If your application makes constant use of the network, it’s probably most efficient to set up a single instance of RequestQueue
that will last the lifetime of your app. You can achieve this in various ways. The recommended approach is to implement a singleton class that encapsulates RequestQueue
and other Volley functionality.
A key concept is that the RequestQueue
must be instantiated with the Application
context, not an Activity
context. This ensures that the RequestQueue
will last for the lifetime of your app, instead of being recreated every time the activity is recreated (for example, when the user rotates the device).
Create java class in your application named VolleySingleton.java And paste following code into it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
package com.example.volley; import android.app.Application; import android.text.TextUtils; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; public class VolleySingleton extends Application { public static final String TAG = VolleySingleton.class.getSimpleName(); private RequestQueue mRequestQueue; 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; } 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 add highlighted lines to AndroidManifest.xml . Text added to line no. 13 will allow you to execute this class automatically whenever app launches.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.volley" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="24" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:name="com.example.volley.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> |
3. Setting up UI.
We will be needing two buttons to request for string and JSON object from internet and a text view to show the fetched result . Now add following code to activity_main.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<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="com.example.volley.MainActivity" > <Button android:id="@+id/buttonLoadString" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="Request String" /> <Button android:id="@+id/buttonJSONRequest" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/buttonLoadString" android:layout_below="@+id/buttonLoadString" android:text="Request JSON object" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/buttonJSONRequest" android:layout_below="@+id/buttonJSONRequest" android:layout_marginTop="28dp" /> </RelativeLayout><br> |
4. Creating helper classes
Now create a class named NetworkStringLoader.java and add following code to it. This class is helper class for downloading String from network. Afterwards just create its object and request for string just by passing url to requestString
method of this object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
package com.cointribe.account.services; import android.app.ProgressDialog; import android.content.Context; import android.widget.TextView; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; public class NetworkStringLoader { Context context; TextView display; public NetworkStringLoader(Context con, TextView tv) { context = con; display = tv; } public void requestString(String url) { // Tag used to cancel the request String tag_string_req = "string_req"; final ProgressDialog pDialog = new ProgressDialog(context); pDialog.setMessage("Loading..."); pDialog.show(); StringRequest strReq = new StringRequest(Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { display.setText(response); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { display.setText(error.toString()); pDialog.hide(); } }); // Adding request to request queue VolleySingleton.getInstance().addToRequestQueue(strReq, tag_string_req); } } |
Now create other helper class NetworkJSONLoader.java and copy following code to it. This will be used to download JSON object from specified URL.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package com.example.volley; import org.json.JSONObject; import android.app.ProgressDialog; import android.content.Context; import android.widget.TextView; import com.android.volley.Request.Method; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; public class NetworkJSONLoader { Context context; TextView display; public NetworkJSONLoader(Context con, TextView tv) { context = con; display = tv; } public void requestJSON(String url) { // Tag used to cancel the request String tag_json_obj = "json_obj_req"; final ProgressDialog pDialog = new ProgressDialog(context); pDialog.setMessage("Loading..."); pDialog.show(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { display.setText(response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { display.setText(error.toString()); pDialog.hide(); } }); // Adding request to request queue VolleySingleton.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj); } } |
5. Connecting it all
Now open MainActivity.java and paste this code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
package com.example.volley; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { String urlString = "http://cs2guru.com/api/sample_files/sample.html"; String urlJSON = "http://cs2guru.com/api/sample_files/sample.json"; Button stringLoaderBtn, jsonLoaderBtn; TextView tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.textView1); stringLoaderBtn = (Button) findViewById(R.id.buttonLoadString); stringLoaderBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { NetworkStringLoader loader = new NetworkStringLoader( MainActivity.this, tv); loader.requestString(urlString); } }); jsonLoaderBtn = (Button) findViewById(R.id.buttonJSONRequest); jsonLoaderBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { NetworkJSONLoader j = new NetworkJSONLoader(MainActivity.this, tv); j.requestJSON(urlJSON); } }); } } |
6. Build and run the project
You will be able to download data from network using volley library.