StringRequest Volley - Retrieve Response as String

Volley is an Android HTTP networking library. In the previous article, we had a glimpse of the Volley library and performed a POST request using JsonObjectRequest.

In this article, we will fetch the response as string from https://reqres.in/api/users/2 and display it as the TextView text. For this purpose, we will be using StringRequest which makes a GET request to an endpoint and returns the response as a string.

// Build the request
final StringRequest stringRequest = new StringRequest(URL_USER, new Response.Listener<String>() {
    @Override
    public void onResponse(@NonNull String response) {
        // Api call successful
        Log.d(TAG, "Response: " + response);
        // Show the response on the screen
        responseTextView.setText(response);
    }
}, new Response.ErrorListener() {
  @Override
  public void onErrorResponse(@NonNull VolleyError error) {
    // Api call failed
    // Print the error to stacktrace
    error.printStackTrace();
    // Show the error to the user
    Snackbar.make(mainConstraintLayout, "Error: " + error.getMessage(), Snackbar.LENGTH_SHORT).show();
  }
});

// Make the request
Volley.newRequestQueue(this).add(stringRequest);

onResponse callback is triggered when the Api calls succeed and we update the TextView as shown in the image. Otherwise, onErrorResponse is called and we will display a snack message to the user.

volley-main-screen

If you are interested to explore the code, feel free to fork the Volley Request project available on Github.

Popular posts from this blog

How to Read Metadata from AndriodManifest File

Mr Phone - Find The Next Best Phone You Want To Buy

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Add Options Menu to Activity and Fragment

Create Assets Folder, Add Files and Read Data From It