Networking with Volley in Android


Volley is a networking library for Android that manages network requests. It bundles the most important features you’ll need, such as accessing JSON APIs, loading images and String requests in an easier-to-use package.
By using Volley for network operations you avoid the standard way to handle networking, HttpURLConnection. Another reason is asynchronicity. Volley handles asynchronicity by itself, there is no need to create Asynctask manually.

Import Volley, add Permissions


dependencies { ...... implementation'com.android.volley:volley:1.0.0' }
------------------------------------------------------------------------
In AndroidManifest.xml add the internet permission.
<uses-permission android:name="android.permission.INTERNET" />
------------------------------------------------------------------------
In MainActivity’s onCreate() method, initiate the RequestQueue.
RequestQueue requestQueue;
@Override
protected void onCreate(Bundle savedInstanceState)
{
//...
requestQueue = Volley.newRequestQueue(this); }
------------------------------------------------------------------------
Volley has Requests for JSONObject and JSONArray. The structure of JSONRequest
and most of the request classes included in Volley uses constructors like
the following.
JsonObjectRequest request JsonObjectRequest(RequestMethod,
URL,
null,
new ResponseListener(),
new ErrorListener());
----------------------------------------------------------------------------
JsonObjectRequest
/*Json Request*/
String url = "https://json_url/";
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
url,
null,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) { }
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) { }
});
//add request to queue
requestQueue.add(jsonObjectRequest);
JsonArrayRequest
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET,
url,
null,
new Response.Listener<JSONArray>()
{
@Override
public void onResponse(JSONArray response) { }
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) { }
});
//add request to queue
requestQueue.add(jsonArrayRequest);

Comments :

Post a Comment