Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaMaking API Calls using Volley Library in Android

Making API Calls using Volley Library in Android

Volley is an HTTP library that’s used for caching and making a network request in Android applications. It is an HTTP library that makes networking for Android apps easier and most importantly, faster. API stands for Application Programming Interface. It is a way for two or more computer programs to communicate with each other. By using its products or services communicate with other products and services without having to know how they’re implemented. 

Note: This Android article covered in both Java and Kotlin languages. 

Step By Step Implementation:

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Add internet permission to your app

Go to app > manifest.xml file and add the internet permission. Below is the code for the manifest file.

XML




<?xml version="1.0" encoding="utf-8"?>
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.gfgvolleyapicall">
  
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.GFGvolleyApiCall">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            tools:ignore="WrongManifestParent">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
  
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <!-- adding internet permission -->
    <uses-permission android:name="android.permission.INTERNET"/>  
</manifest>


Step 3: Add the Volley dependency to build.gradle (Module : app ) file

Go to app > Gradle Scripts > build.gradle (Module : app) file and add the dependency. Below is the code for the build.gradle file.

plugins {
   id ‘com.android.application’
}

android {
   compileSdk 31

   defaultConfig {
       applicationId “com.example.gfgvolleyapicall”
       minSdk 21
       targetSdk 31
       versionCode 1
       versionName “1.0”

       testInstrumentationRunner “androidx.test.runner.AndroidJUnitRunner”
   }

   buildTypes {
       release {
           minifyEnabled false
           proguardFiles getDefaultProguardFile(‘proguard-android-optimize.txt’), ‘proguard-rules.pro’
       }
   }
   compileOptions {
       sourceCompatibility JavaVersion.VERSION_1_8
       targetCompatibility JavaVersion.VERSION_1_8
   }
}

dependencies {

   implementation ‘androidx.appcompat:appcompat:1.4.2’
   implementation ‘com.google.android.material:material:1.6.1’
   implementation ‘androidx.constraintlayout:constraintlayout:2.1.4’
   testImplementation ‘junit:junit:4.13.2’
   androidTestImplementation ‘androidx.test.ext:junit:1.1.3’
   androidTestImplementation ‘androidx.test.espresso:espresso-core:3.4.0’

   implementation ‘com.android.volley:volley:1.2.1’     // adding volley dependency 
}

Step 4: Working with activity_main.xml

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:backgroundTint="@color/white"
        app:layout_constraintTop_toTopOf="parent">
  
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
  
            <TextView
                android:id="@+id/textView3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:textColor="@color/purple_700"
                android:textSize="20sp"
                android:textAlignment="center"
                android:text="welcome to geeks for geeks" />
        </LinearLayout>
        
    </LinearLayout>
    
</androidx.constraintlayout.widget.ConstraintLayout>


Step 5: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail.

Java




package com.example.gfgvolleyapicall;
  
import static android.content.ContentValues.TAG;
  
import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
import android.util.Log;
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.StringRequest;
import com.android.volley.toolbox.Volley;
  
public class MainActivity extends AppCompatActivity {
    private RequestQueue mRequestQueue;
    private StringRequest mStringRequest;
      
      @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        getData();
    }
  
    private void getData() {
        // RequestQueue initialized
        mRequestQueue = Volley.newRequestQueue(this);
          
          // String Request initialized
        mStringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
  
                Toast.makeText(getApplicationContext(), "Response :" + response.toString(), Toast.LENGTH_LONG).show();//display the response on screen
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i(TAG, "Error :" + error.toString());
            }
        });
  
        mRequestQueue.add(mStringRequest);
    }
}


Kotlin




package com.example.gfgvolleyapicall;
  
import static android.content.ContentValues.TAG;
  
import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
import android.util.Log;
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.StringRequest;
import com.android.volley.toolbox.Volley;
  
class MainActivity : AppCompatActivity() {
    private var mRequestQueue: RequestQueue? = null
    private var mStringRequest: StringRequest? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        getData()
    }
  
    private fun getData() {
        // RequestQueue initialized
        mRequestQueue = Volley.newRequestQueue(this)
          
        // String Request initialized
        mStringRequest = StringRequest(Request.Method.GET, url, object : Listener<String?>() {
            // display the response on screen
            fun onResponse(response: String) {
                Toast.makeText(applicationContext, "Response :$response", Toast.LENGTH_LONG)
                    .show() 
            }
        }, object : ErrorListener() {
            fun onErrorResponse(error: VolleyError) {
                Log.i(ContentValues.TAG, "Error :" + error.toString())
            }
        })
        mRequestQueue.add(mStringRequest)
    }
}


Output:

Previous article
Next article
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments