How to send POST requests with JSON data using Volley in Android?


Most of the android applications we see on Google Play store make an API call within themselves so that they can gather data from their database and display that within our application. Similarly many applications take the data from the user through forms and store them within their database. Many applications take user details such as address and other for delivering specific products to their address. For posting this data there are different ways such as using Volley, Retrofit and others. In this article we will take a look on How to send POST requests with JSON data using Volley in Android.

Implementation

We will be creating a simple application in which we will be displaying two edit text fields and a button. User has to enter a name and job in these text fields and click on the button to submit this data. Then we will be sending this data to the API by making a POST request using Volley in Android. We will be using a sample API to make this POST request API call which will help us to post the data. After posting this data we will also receive the response from the API which will be displayed within our application.

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:id="@+id/idRLLayout"
   android:layout_width="match_parent"
   android:layout_height="match_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_marginStart="10dp"
       android:layout_marginTop="100dp"
       android:layout_marginEnd="10dp"
       android:gravity="center"
       android:text="POST Request using Volley"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp"
       android:textStyle="bold" />

   <!-- on below line creating edit text for name -->
   <EditText
       android:id="@+id/idEdtName"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_margin="10dp"
       android:hint="Enter your Name"
       android:textAllCaps="false" />

   <!-- on below line creating edit text for name -->
   <EditText
       android:id="@+id/idEdtJob"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtName"
       android:layout_margin="10dp"
       android:hint="Enter your Job"
       android:textAllCaps="false" />

   <!-- progress bar for displaying a loading indicator -->
   <ProgressBar
       android:id="@+id/idPBLoading"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:indeterminate="true"
       android:indeterminateTint="@color/black"
       android:visibility="gone" />

   <!-- button for posting the data -->
   <Button
       android:id="@+id/idBtnPostData"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtJob"
       android:layout_margin="10dp"
       android:text="Post Data"
       android:textAllCaps="false" />

   <!-- tyext view for displaying the response -->
   <TextView
       android:id="@+id/idTVResponse"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idBtnPostData"
       android:layout_margin="10dp"
       android:gravity="center"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp"
       android:textStyle="bold" />
</RelativeLayout>

Explanation : In the above code the root element is a Relative layout in android. Inside this relative layout we are creating a simple text view which we will be using to display the heading of our application. After that we are creating two edit text fields which will be used to take the data from the user through the keyboard which we have to post. The first edit text will be used to get the name and the second edit text will be used to get the job from the user. After that we are displaying a progress bar which is used as a loading indicator while posting the data. After this progress bar we are displaying a button which is used to post the data, on clicking this button we will be posting the data to our server. After that we will be creating one more text view inside which we will be displaying the response from our API.

Step 4 : Adding internet permissions in AndroidManifest.xml file

As we are getting data from the internet 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 android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.AuthFailureError;
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.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
   // on below line we are creating variables
   private EditText nameEdt, jobEdt;
   private Button postDataBtn;
   private ProgressBar loadingPB;
   private TextView responseTV;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_main);
       // on below line initializing variable with id.
       nameEdt = findViewById(R.id.idEdtName);
       jobEdt = findViewById(R.id.idEdtJob);
       postDataBtn = findViewById(R.id.idBtnPostData);
       loadingPB = findViewById(R.id.idPBLoading);
       responseTV = findViewById(R.id.idTVResponse);
       // on below line adding click listner for our post data button.
       postDataBtn.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // on below line checking of the edit text is empty or not.
               if (nameEdt.getText().toString().isEmpty() && jobEdt.getText().toString().isEmpty()) {
                   Toast.makeText(MainActivity.this, "Pplease enter name and job..", Toast.LENGTH_SHORT).show();
               } else {
                   // on below line calling method to post the data.
                   postDataUsingVolley(nameEdt.getText().toString(), jobEdt.getText().toString());
               }
           }
       });
   }
   private void postDataUsingVolley(String name, String job) {
       // on below line specifying the url at which we have to make a post request
       String url = "https://reqres.in/api/users";
       // setting progress bar visibility on below line.
       loadingPB.setVisibility(View.VISIBLE);
       // creating a new variable for our request queue
       RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
       // making a string request on below line.
       StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
           @Override
           public void onResponse(String response) {
               // channing progress bar visibility on below line.
               loadingPB.setVisibility(View.GONE);
               // setting response to text view.
               responseTV.setText("Response from the API is :
" + response); // displaying toast message. Toast.makeText(MainActivity.this, "Data posted succesfully..", Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // handling error on below line. loadingPB.setVisibility(View.GONE); responseTV.setText(error.getMessage()); Toast.makeText(MainActivity.this, "Fail to get response..", Toast.LENGTH_SHORT).show(); } }) { @Nullable @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<String, String>(); // on below line we are passing our key // and value pair to our parameters. params.put("name", name); params.put("job", job); return params; } }; // adding request to queue to post the data. queue.add(request); } }

Explanation : In the above code for the MainActivity.java file. Firstly we are creating variables for our text view, button, progress bar and edit text. Inside the onCreate method we are initializing our variables with the ids which we have given in the activity_main.xml file. After initializing all variables we are adding a click listener for our button. Inside the click listener method we are checking whether the edit text is empty or not. If the edit text fields are empty in that case we are displaying a toast message to enter the data in the edit text fields. If the text fields are not empty in that case we are calling the post data method to post the data.

Inside the post data using volley method we are passing two variables as name and job. In this method we are firstly creating a string variable for the URL of the API on which we have to make a post request. After that we are changing the visibility of our progress bar. Then we are initializing our request queue variable and creating a new request queue. Then we are making a string request inside which we are specifying the request type as post request and then specifying the url. Now inside the response method we are displaying the response inside our text view. Similarly we are handling the error method. We are displaying the error message on our text view. Then we are calling the get params method in which we are setting the data which we have to post to the API. Inside this we are passing our name and job to post to the API. Lastly we are adding this request to the queue to post the data.

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 code we have taken a look on How to post the data to API using JSON response in android. Along with that we have also taken a look on How to use Volley library to post the data.

Updated on: 09-May-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements