How can I do a synchronous request with Volley in Android?


What is a synchronous request in Android

Synchronous requests with Volley in Android App can be useful for developers who wish to retrieve data from a server and be able to immediately use it in their application. This can be useful for tasks such as loading images or data from a remote server. In this article, we will discuss how to make synchronous requests with Volley in an Android App

Implementation of a Synchronous request in Android

We will be creating a simple application in which we will be simply displaying two text views. In the first text view we will be displaying the heading of our application and in the second text view we will be displaying the response from our API call.

Step 1: Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Java. After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2: Adding dependency in build.gradle file to use this library

Navigate to Gradle Scripts>build.gradle file and add the below dependency in dependencies section.

implementation 'com.android.volley:volley:1.2.1'

In the dependencies section we will be adding a dependency which is used to get data from API calls to load it within our application.

After adding the above dependency you will get to see the Sync Now option in the top right corner of your IDE. Simply click on it to sync your project and install this dependency within your project.

Step 3: Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- on below line creating a text view for displaying a heading-->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_above="@id/idTVMsg"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="Synchronous Request in Android App with Volley"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="20sp"
      android:textStyle="bold" />

   <!-- on below line creating a text view for displaying a message from API call-->
   <TextView
      android:id="@+id/idTVMsg"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="18sp" />

</RelativeLayout>

Explanation − In the above code the root element is a Relative layout in android. This layout is a view group which is used to align all the elements within it relative to each other. We can relatively align all elements within Relative Layout with the help of ids or positions.

Inside this relative layout we are creating two text views. The first text view is used to display the heading of our application. In the second text view we will be displaying the response from our API call within our application.

Step 4 : Adding internet permissions in AndroidManifest.xml file

As we are getting data from the internet using URLs we have to add internet permissions within our android application to access the internet to load this data. So we have to add internet permission. For adding internet permissions. Navigate to app>AndroidManifest.xml file and add below permission to it above the application tag.

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

Step 7: Working with MainActivity.java

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>java>your app’s package name>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.androidjavaapp;

import androidx.appcompat.app.AppCompatActivity;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
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.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {
   
   // on below line creating a variables
   private TextView msgTV;
   String url = "https://www.jsonkeeper.com/b/N6XK";

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      // on below line initializing web view with id.
      msgTV = findViewById(R.id.idTVMsg);
      
      // on below line we are making a json object request and specifying the method name as get, url on which we are making request
      JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
         @Override
         public void onResponse(JSONObject response) {
            
            // in on response method we are setting response data to our text view.
               try {
                  msgTV.setText(response.getString("message"));
               } catch (JSONException e) {
                  
                  // on below line handling error.
                  e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
          @Override
          public void onErrorResponse(VolleyError error) {
             // on below line displaying toast message for error.
             Toast.makeText(MainActivity.this, "Error : " + error, Toast.LENGTH_SHORT).show();
          }
      });
      // on below line adding request to volley request queue.
      Volley.newRequestQueue(getApplicationContext()).add(jsonObjectRequest);
   }
}

Explanation − In the above code for the MainActivity.java file. Firstly we are creating a variable for our text view in which we are displaying a text message. After that we are creating a variable for string in which we are adding a url through which we will get the json response.

Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file.

After specifying the view we are initializing our text view with its unique id which we have given in the activity_main.xml file.

After initializing our variables we are making a json object request. Inside this method we are making a get request and passing the url to it on which we have to make a request. Inside the on response method we are parsing the json response and setting it to our text view. After that we are also creating an error listener method. Inside which we are displaying a toast message when any error is received. Lastly we are adding this json object request to the queue to execute it.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above tutorial we have taken a look at How to do a synchronous request in android application using Volley as a library.

Updated on: 30-Mar-2023

551 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements