This lesson teaches you to
Video
Volley: Easy, Fast Networking for Android
This lesson describes how to use the common request types that Volley supports:
StringRequest
. Specify a URL and receive a raw string in response. See Setting Up a Request Queue for an example.JsonObjectRequest
andJsonArrayRequest
(both subclasses ofJsonRequest
). Specify a URL and get a JSON object or array (respectively) in response.
If your expected response is one of these types, you probably don't have to implement a custom request. This lesson describes how to use these standard request types. For information on how to implement your own custom request, see Implementing a Custom Request.
Request JSON
Volley provides the following classes for JSON requests:
JsonArrayRequest
—A request for retrieving aJSONArray
response body at a given URL.JsonObjectRequest
—A request for retrieving aJSONObject
response body at a given URL, allowing for an optionalJSONObject
to be passed in as part of the request body.
Both classes are based on the common base class JsonRequest
. You use them
following the same basic pattern you use for other types of requests. For example, this
snippet fetches a JSON feed and displays it as text in the UI:
Kotlin
val url = "http://my-json-feed" val jsonObjectRequest = JsonObjectRequest(Request.Method.GET, url, null, Response.Listener { response -> textView.text = "Response: %s".format(response.toString()) }, Response.ErrorListener { error -> // TODO: Handle error } ) // Access the RequestQueue through your singleton class. MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)
Java
String url = "http://my-json-feed"; JsonObjectRequest jsonObjectRequest = new JsonObjectRequest (Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { mTextView.setText("Response: " + response.toString()); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // TODO: Handle error } }); // Access the RequestQueue through your singleton class. MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest);