Friday, December 27, 2024
Google search engine
HomeGuest BlogsBuild an Android App to Check COVID-19 Vaccination Availability

Build an Android App to Check COVID-19 Vaccination Availability

Pre-requisites:

The government of India has started the biggest vaccination drive across India to give vaccination to people to fight against the COVID-19 virus. As there are so many vaccination centers in India for vaccination so to check the availability of different vaccination in different centers across India. We will be building a simple application for getting the details about vaccination centers in India.

Build-an-Android-App-to-Check-COVID-19-Vaccination-Availability

What we will be building in this article? 

We will be building a simple application in which we will be getting the data for the vaccination centers from the Pincode of that location. Below is the video in which we will get to see what we are going to build in this article. Note that we are going to implement this project using the Kotlin language. 

Step 1: Opening a new project

  • Open a new project just click of File option at the topmost corner in the left.
  • Then click on new and open a new project with whatever name you want.
  • Now we gonna work on Empty Activity with language as Kotlin. Leave all other options untouched.
  • You can change the name of the project as per your choice
  • By default, there will be two files activity_main.xml and MainActivity.java.

Or To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Before going to the coding section first you have to do some pre-task

Go to the app  > res > values > colors.xml section and set the colors for your app.

XML




<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#0F9D58</color>
    <color name="purple_500">#0F9D58</color>
    <color name="purple_700">#0F9D58</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>
</resources>


Step 3: Adding dependency for Volley in build.gradle file

Go to Gradle Scripts > build.gradle (Module: app) section and import the following dependencies and click the “sync Now” on the above pop-up. We have used the Volley library in this project. 

// Volley library
implementation 'com.android.volley:volley:1.1.1'

Step 4: Adding Internet Permissions in the AndroidManifest.xml file 

Navigate to the app > AndroidManifest.xml file and add the below line of code in it.  

XML




<!--Allow Internet Permission-->
<uses-permission android:name="android.permission.INTERNET" />


 
Step 5: Working with the activity_main.xml file

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"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <!--edit text for entering the pin code-->
    <EditText
        android:id="@+id/idEdtPinCode"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_toStartOf="@id/idBtnSearch"
        android:layout_toLeftOf="@id/idBtnSearch"
        android:hint="Enter PinCode"
        android:inputType="number" />
 
    <!--button for searching the data-->
    <Button
        android:id="@+id/idBtnSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_margin="5dp"
        android:background="@color/purple_200"
        android:text="Search"
        android:textAllCaps="false" />
 
    <!--progress bar for loading indicator-->
    <ProgressBar
        android:id="@+id/idPBLoading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:visibility="gone" />
 
    <!--recycler view for displaying results in the form of list-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/centersRV"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/idEdtPinCode"
        tools:listitem="@layout/center_rv_item" />
 
</RelativeLayout>


 
Step 6: Creating a new Kotlin file for storing our data

We have to store the data in a modal class for that we will be creating a new Kotlin class file. For creating this file. Navigate to the app > java > your app’s package name > Right-click on it > New > Kotlin File/Class option and then choose Class and name your file as CenterRvModal and add the below code to it. Comments are added in the code to get to know in more detail. 

Kotlin




data class CenterRvModal(
 
        // string variable for center name.
        val centerName: String,
 
        // string variable for center address.
        val centerAddress: String,
 
        // string variable for center opening time.
        val centerFromTime: String,
 
        // string variable for center closing time.
        val centerToTime: String,
 
        // string variable for center fee type
        var fee_type: String,
 
        // int variable for age limit.
        var ageLimit: Int,
 
        // string variable for vaccination name.
        var vaccineName: String,
 
        // int variable for vaccine availability.
        var availableCapacity: Int
)


Step 7: Creating a new layout file for our item of RecyclerView

Navigate to app >res > layout > Right-click on it > New > Layout file and name it as center_rv_item and add below code to it. Comments are added in the code to get to know in more detail. The below layout file can be used to display each item of our RecyclerView.  

Note: Images used in the project are present in the drawable folder. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="4dp">
 
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
 
        <!--text view for displaying center name-->
        <TextView
            android:id="@+id/idTVCenterName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:drawableLeft="@drawable/ic_hospital"
            android:drawablePadding="4dp"
            android:padding="3dp"
            android:text="Center Name"
            android:textColor="@color/black" />
 
        <!--text view for displaying center address-->
        <TextView
            android:id="@+id/idTVCenterAddress"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVCenterName"
            android:layout_margin="3dp"
            android:drawableLeft="@drawable/ic_location"
            android:drawablePadding="4dp"
            android:padding="3dp"
            android:text="Center Address"
            android:textColor="@color/black" />
 
        <!--text view for displaying center timings-->
        <TextView
            android:id="@+id/idTVCenterTimings"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVCenterAddress"
            android:layout_margin="3dp"
            android:drawableLeft="@drawable/ic_time"
            android:drawablePadding="4dp"
            android:padding="3dp"
            android:text="Timings"
            android:textColor="@color/black" />
 
        <LinearLayout
            android:id="@+id/idLL1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVCenterTimings"
            android:orientation="horizontal"
            android:weightSum="2">
 
            <!--text view for displaying vaccine name-->
            <TextView
                android:id="@+id/idTVVaccineName"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_margin="3dp"
                android:layout_weight="1"
                android:drawableLeft="@drawable/ic_vaccine"
                android:drawablePadding="4dp"
                android:padding="3dp"
                android:text="Vaccine Name"
                android:textColor="@color/black" />
 
            <!--text view for displaying center fees type-->
            <TextView
                android:id="@+id/idTVFeeType"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="3dp"
                android:layout_weight="1"
                android:padding="3dp"
                android:text="Fee Type"
                android:textAlignment="center"
                android:textColor="@color/black" />
        </LinearLayout>
 
        <LinearLayout
            android:id="@+id/idLL2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idLL1"
            android:orientation="horizontal"
            android:weightSum="2">
             
            <!--text view for displaying age limit-->
            <TextView
                android:id="@+id/idTVAgeLimit"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="3dp"
                android:layout_weight="1"
                android:padding="3dp"
                android:text="Age Limit"
                android:textAlignment="center"
                android:textColor="@color/black" />
             
            <!--text view for displaying center availability-->
            <TextView
                android:id="@+id/idTVAvailability"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:layout_margin="3dp"
                android:layout_weight="1"
                android:padding="3dp"
                android:text="Availability"
                android:textAlignment="center"
                android:textColor="@color/black" />
 
        </LinearLayout>
         
    </RelativeLayout>
     
</androidx.cardview.widget.CardView>


 
Step 8: Creating a new Kotlin file for our Adapter class

Now for setting data to each item of our Recycler View. We have to create a new adapter class for setting data to each item of our Recycler View. For creating a new Kotlin file, navigate to the app > java > your app’s package name > Right-click on it > New > Kotlin File/Class and name it as CenterRVAdapter and add the below code to it. Comments are added in the code to get to know in more detail. 

Kotlin




import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
 
// on below line we are creating our adapter class
// in this class we are passing our array list
// and our View Holder class which we have created.
class CenterRVAdapter(private val centerList: List<CenterRvModal>) :
        RecyclerView.Adapter<CenterRVAdapter.CenterRVViewHolder>() {
 
    // on below line we are creating our view holder class which will
    // be used to initialize each view of our layout file.
    class CenterRVViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // on below line we are initializing all our text views along with  its ids.
        val centerNameTV: TextView = itemView.findViewById(R.id.idTVCenterName)
        val centerAddressTV: TextView = itemView.findViewById(R.id.idTVCenterAddress)
        val centerTimings: TextView = itemView.findViewById(R.id.idTVCenterTimings)
        val vaccineNameTV: TextView = itemView.findViewById(R.id.idTVVaccineName)
        val centerAgeLimitTV: TextView = itemView.findViewById(R.id.idTVAgeLimit)
        val centerFeeTypeTV: TextView = itemView.findViewById(R.id.idTVFeeType)
        val availabilityTV: TextView = itemView.findViewById(R.id.idTVAvailability)
    }
 
    // below method is for on Create View Holder.
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CenterRVViewHolder {
        // this method is use to inflate the layout file
        // which we have created for our recycler view.
        // on below line we are inflating our layout file.
        val itemView = LayoutInflater.from(parent.context).inflate(
                R.layout.center_rv_item,
                parent, false
        )
        // at last we are returning our view holder
        // class with our item View File.
        return CenterRVViewHolder(itemView)
    }
 
    // this method is to count the size of our array list.
    override fun getItemCount(): Int {
 
        // on below line we are returning
        // the size of our array list.
        return centerList.size
    }
 
    // below method is to set the data to each view of our recycler view item.
    override fun onBindViewHolder(holder: CenterRVViewHolder, position: Int) {
 
        // on below line we are getting item
        // from our list along with its position.
        val currentItem = centerList[position]
 
        // after getting current item we are setting
        // data from our list to our text views.
        holder.centerNameTV.text = currentItem.centerName
        holder.centerAddressTV.text = currentItem.centerAddress
        holder.centerTimings.text = ("From : " + currentItem.centerFromTime + " To : " + currentItem.centerToTime)
        holder.vaccineNameTV.text = currentItem.vaccineName
        holder.centerAgeLimitTV.text = "Age Limit : " + currentItem.ageLimit.toString()
        holder.centerFeeTypeTV.text = currentItem.fee_type
        holder.availabilityTV.text = "Availability : " + currentItem.availableCapacity.toString()
    }
}


 
Step 9: Working with MainActivity.kt file. 

Navigate to the app > java > your app’s package name > MainActivity.kt file and add the below code to it. Comments are added in the code to get to know in more detail.  

Kotlin




import android.app.DatePickerDialog
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.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.volley.Request
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import org.json.JSONException
import java.util.*
import kotlin.collections.ArrayList
 
class MainActivity : AppCompatActivity() {
     
    // creating a variable for our button.
    private lateinit var searchButton: Button
 
    // creating variable for our edit text.
    lateinit var pinCodeEdt: EditText
 
    // creating a variable for our recycler view.
    lateinit var centersRV: RecyclerView
 
    // creating a variable for adapter class.
    lateinit var centerRVAdapter: CenterRVAdapter
 
    // creating a variable for our list
    lateinit var centerList: List<CenterRvModal>
 
    // creating a variable for progress bar.
    lateinit var loadingPB: ProgressBar
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // inside on create method we are initializing
        // all our variables which we have declared.
        searchButton = findViewById(R.id.idBtnSearch)
        pinCodeEdt = findViewById(R.id.idEdtPinCode)
        centersRV = findViewById(R.id.centersRV)
        loadingPB = findViewById(R.id.idPBLoading)
        centerList = ArrayList<CenterRvModal>()
         
        // on below line we are adding on
        // click listener to our button.
        searchButton.setOnClickListener {
 
            // inside on click listener we are getting data from
            // edit text and creating a val for ite on below line.
            val pinCode = pinCodeEdt.text.toString()
 
            // on below line we are validating
            // our pin code as 6 digit or not.
            if (pinCode.length != 6) {
 
                // this method is called when users enter invalid pin code.
                Toast.makeText(this@MainActivity, "Please enter valid pin code", Toast.LENGTH_SHORT).show()
            } else {
 
                // if the pincode is correct.
                // first of all we are clearing our array list this
                // will clear the data in it if already present.
                (centerList as ArrayList<CenterRvModal>).clear()
 
                // on below line we are getting instance of our calendar.
                val c = Calendar.getInstance()
 
                // on below line we are getting our current year, month and day.
                val year = c.get(Calendar.YEAR)
                val month = c.get(Calendar.MONTH)
                val day = c.get(Calendar.DAY_OF_MONTH)
 
                // on below line we are creating our date picker dialog.
                val dpd = DatePickerDialog(
                        this,
                        DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
                            // after that we are making our progress bar as visible.
                            loadingPB.setVisibility(View.VISIBLE)
 
                            // on below line we are creating a date string for our date
                            val dateStr: String = """$dayOfMonth - ${monthOfYear + 1} - $year"""
 
                            // on below line we are calling a method to get
                            // the appointment info for vaccination centers
                            // and we are passing our pin code to it.
                            getAppointments(pinCode, dateStr)
                        },
                        year,
                        month,
                        day
                )
                // calling a method to display
                // our datepicker dialog.
                dpd.show()
            }
        }
    }
 
    // below is the method for getting data from API.
    private fun getAppointments(pinCode: String, date: String) {
        val url = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode=" + pinCode + "&date=" + date
        val queue = Volley.newRequestQueue(this@MainActivity)
         
        // on below line we are creating a request
        // variable for making our json object request.
        val request =
                // as we are getting json object response and we are making a get request.
                JsonObjectRequest(Request.Method.GET, url, null, { response ->
                    // this method is called when we get successful response from API.
                    Log.e("TAG", "SUCCESS RESPONSE IS $response")
                    // we are setting the visibility of progress bar as gone.
                    loadingPB.setVisibility(View.GONE)
                    // on below line we are adding a try catch block.
                    try {
                        // in try block we are creating a variable for center
                        // array and getting our array from our object.
                        val centerArray = response.getJSONArray("centers")
 
                        // on below line we are checking if the length of the array is 0.
                        // the zero length indicates that there is no data for the given pincode.
                        if (centerArray.length().equals(0)) {
                            Toast.makeText(this, "No Center Found", Toast.LENGTH_SHORT).show()
                        }
                        for (i in 0 until centerArray.length()) {
 
                            // on below line we are creating a variable for our center object.
                            val centerObj = centerArray.getJSONObject(i)
 
                            // on below line we are getting data from our session
                            // object and we are storing that in a different variable.
                            val centerName: String = centerObj.getString("name")
                            val centerAddress: String = centerObj.getString("address")
                            val centerFromTime: String = centerObj.getString("from")
                            val centerToTime: String = centerObj.getString("to")
                            val fee_type: String = centerObj.getString("fee_type")
 
                            // on below line we are creating a variable for our session object
                            val sessionObj = centerObj.getJSONArray("sessions").getJSONObject(0)
                            val ageLimit: Int = sessionObj.getInt("min_age_limit")
                            val vaccineName: String = sessionObj.getString("vaccine")
                            val availableCapacity: Int = sessionObj.getInt("available_capacity")
 
                            // after extracting all the data we are passing this
                            // data to our modal class we have created
                            // a variable for it as center.
                            val center = CenterRvModal(
                                    centerName,
                                    centerAddress,
                                    centerFromTime,
                                    centerToTime,
                                    fee_type,
                                    ageLimit,
                                    vaccineName,
                                    availableCapacity
                            )
                            // after that we are passing this modal to our list on the below line.
                            centerList = centerList + center
                        }
 
                        // on the below line we are passing this list to our adapter class.
                        centerRVAdapter = CenterRVAdapter(centerList)
                         
                        // on the below line we are setting layout manager to our recycler view.
                        centersRV.layoutManager = LinearLayoutManager(this)
                         
                        // on the below line we are setting an adapter to our recycler view.
                        centersRV.adapter = centerRVAdapter
                         
                        // on the below line we are notifying our adapter as the data is updated.
                        centerRVAdapter.notifyDataSetChanged()
 
                    } catch (e: JSONException) {
                        // below line is for handling json exception.
                        e.printStackTrace();
                    }
                },
                        { error ->
                            // this method is called when we get any
                            // error while fetching data from our API
                            Log.e("TAG", "RESPONSE IS $error")
                            // in this case we are simply displaying a toast message.
                            Toast.makeText(this@MainActivity, "Fail to get response", Toast.LENGTH_SHORT).show()
                        })
        // at last we are adding
        // our request to our queue.
        queue.add(request)
    }
}


 
Now run your app and see the output of the app 

Output:  

Note: Our application will currently display the data available for the current date. 

 

Last Updated :
28 Jan, 2022
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

RELATED ARTICLES

Most Popular

Recent Comments