📜 ⬆️ ⬇️

A simple example of using the Volley library

I’m sure you haven’t heard the word “Volley” yet, this is the library presented on Google I / O 2013 Ficus Kirkpatrick .

What is the Volley library for?


Volley is a library that makes Android network applications easier and, most importantly, faster.

It manages the processing and caching of network requests, and it saves the precious time of developers from writing the same network request / read code from the cache again and again. And one more advantage, less code, fewer errors :)

Usually we write the same network request code in AsyncTask, the logic of processing the response from the Web API and displaying it in View. We need to take care of displaying the ProgressBar / ProgressDialog inside OnsourceExecute () and OnPostExecute (). I know that this is not a difficult task, but still a routine one. Sometimes it’s boring, even when the base class is defined to control the ProgressBar / ProgressDialog and many other things. So now we can say, Volley can be a powerful alternative to AsyncTask.
')

Advantages of using Volley:


  1. Volley automatically compiles all network requests. Volley will take over all the network requests from your application to fulfill them to retrieve a response or image from websites.
  2. Volley provides disk caching and in-memory caching transparency.
  3. Volley provides a powerful API for canceling a request. You can cancel a single request or set multiple requests for cancellation.
  4. Volley provides powerful change features.
  5. Volley provides debugging and tracing tools.

How to start?


  1. Clone the Volley project.
    git clone https://android.googlesource.com/platform/frameworks/volley 
  2. Import the code into your project .

2 main classes Volley


There are 2 main classes:
  1. Request queue
  2. Request

Request queue: used to send network requests, you can create the request queue class where you want, but, as a rule, it is created at startup time and used as a singleton.

Request: it contains all the necessary details for creating a Web API call. For example: what method to use (GET or POST), request data, response listener, error listener.

Take a look at the JSONObjectRequest method:
  /** * Creates a new request. * @param method the HTTP method to use * @param url URL to fetch the JSON from * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and * indicates no parameters will be posted along with request. * @param listener Listener to receive the JSON response * @param errorListener Error listener, or null to ignore errors. */ public JsonObjectRequest(int method, String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) { super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener, errorListener); } /** * Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is * <code>null</code>, <code>POST</code> otherwise. * * @see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener) */ public JsonObjectRequest(String url, JSONObject jsonRequest, Listener<JSONObject> listener, ErrorListener errorListener) { this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest, listener, errorListener); } 

A simple example of using Volley:


I hope you have already cloned / downloaded the Volley library from the Git repository. Now follow the instructions to create a simple example of extracting a JSON response.

Step 1: Make sure you import the Volley project into Eclipse. Now after the import, we have to make the project a library (Library project), right-click => Properties => Android (left panel).

volley as a library project

Step 2: Create a new VolleyExample project.

Step 3: Right click on VolleyExample and include the Volley library in your project.

Including volley library in Android project

Step 4: Enable the permission to use the Internet in the AndroidManifest.xml file

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

Step 5:
5.1 Create an object of class RequestQueue

 RequestQueue queue = Volley.newRequestQueue(this); 

5.2 Create a JSONObjectRequest with response and error listener.

 String url = "https://www.googleapis.com/customsearch/v1?key=AIzaSyBmSXUzVZBKQv9FJkTpZXn0dObKgEQOIFU&cx=014099860786446192319:t5mr0xnusiy&q=AndroidDev&alt=json&searchType=image"; JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @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 } }); 


5.3 Add your request to RequestQueue.
 queue.add(jsObjRequest); 

All code in the MainActivity.java file
 package com.technotalkative.volleyexamplesimple; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.view.Menu; 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 = "https://www.googleapis.com/customsearch/v1?key=AIzaSyBmSXUzVZBKQv9FJkTpZXn0dObKgEQOIFU&cx=014099860786446192319:t5mr0xnusiy&q=AndroidDev&alt=json&searchType=image"; JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @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 } }); queue.add(jsObjRequest); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is sourcesent. getMenuInflater().inflate(R.menu.main, menu); return true; } } 

Source: https://habr.com/ru/post/188860/


All Articles