Integrating APIs into Your Android App

Introduction

In this article, we are going to see how can we integrate functionality of API in an Android App. It will be a quotes app, which will give different quotes every time someone clicks on next button.
API used in this application is freely available, I have attached the linked below.

What is an API?

Application programming interface better known as API, is like a bridge that allows different applications to communicate and interact with each other. It’s essentially a set of rules and protocols that enables one piece of software to access the services or data provided by another piece of software, without needing to understand how the other software works internally. Api stores data in JSON (JavaScript Object Notation) format. Think of an api as a waiter in restaurant – it takes orders(requests) from customer (app) communicate in the kitchen(service or data provider), and brings back the requested item to the customer.

To use functionality of api we will add few dependencies in our app. In this application, we are using volley library.

build.gradle (:app)

implementation("com.android.volley:volley:1.2.1")

First, let’s design our activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-smallcaps"
        android:gravity="center"
        android:padding="10dp"
        android:text="GOT QUOTES!"
        android:textColor="@color/white"
        android:textSize="40sp"
        android:textStyle="bold" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:ignore="ScrollViewCount,UselessParent"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="-127dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/black"
            android:orientation="vertical">


            <ImageView
                android:id="@+id/imageView"
                android:layout_width="350dp"
                android:layout_height="250dp"
                android:layout_gravity="center"
                android:layout_marginTop="10dp"
                android:src="@drawable/img"
                tools:layout_editor_absoluteX="144dp"
                tools:layout_editor_absoluteY="25dp" />

            <TextView
                android:id="@+id/quote"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="10dp"
                android:gravity="center"
                android:text=""
                android:textColor="@color/white"
                android:textSize="30sp"
                android:textStyle="bold"
                tools:layout_editor_absoluteX="174dp"
                tools:layout_editor_absoluteY="211dp" />

            <TextView
                android:id="@+id/name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="10dp"
                android:text=""
                android:textColor="#B8B5B5"
                android:textSize="20sp" />

            <androidx.appcompat.widget.AppCompatButton
                android:id="@+id/btn"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="30dp"
                android:background="#202932"
                android:text="Generate"
                android:textColor="@color/white" />
        </LinearLayout>
    </ScrollView>
</LinearLayout>


Now let’s create MainActivity.kt

package com.ghanshyam.gameofthronesquotes

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import com.ghanshyam.gameofthronesquotes.databinding.ActivityMainBinding
import org.json.JSONException

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityMainBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.btn.setOnClickListener {
            onClick()
        }
    }

    fun onClick() {
        val queue = Volley.newRequestQueue(this@MainActivity)
        val url = "https://api.gameofthronesquotes.xyz/v1/random"
        val jsonObjectRequest = JsonObjectRequest(
            Request.Method.GET, url, null,
            { response ->
                try {
                    val jsonObject = response.getJSONObject("character")
                    val quote = response.getString("sentence")
                    val names = jsonObject.getString("name")
                    binding.quote.setText(quote)
                    binding.name.setText(names)
                } catch (e: JSONException) {
                    throw RuntimeException(e)
                }
            }) { }
        queue.add(jsonObjectRequest)
    }

}

Code explanation

  1. The app has layout with two TextViews to display the quote and character’s name, and a Button to generate a new quote.
  2. When the Button is clicked, the app sends a request to the specified API endpoint (https://api.gameofthronesquotes.xyz/v1/random) using Volley, a networking library for Android.
  3. Upon receiving a response from the API, the app extracts the quote and character name from the JSON response and updates the corresponding TextViews to display them.

Don’t forget to add below declaration in Android manifest file:

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

without this permission declaration, the app would not be able to access the internet.

Conclusion

It’s was a basic implementation of the API in an android app, but a lot more can be done using api. Search on the internet about free API’s and try out implement them.

Github Link: https://github.com/Ghanshyam32/api-integration.git
API Link: https://api.gameofthronesquotes.xyz/v1/random

Leave a Reply

Your email address will not be published. Required fields are marked *