📜  构建一个 Android 应用程序来检查 COVID-19 疫苗接种的可用性

📅  最后修改于: 2021-10-19 08:27:52             🧑  作者: Mango

先决条件:

  • 面向初学者的 Android 应用开发基础
  • 安装和设置 Android Studio 指南
  • 安卓 |如何在 Android Studio 中创建/启动新项目?
  • 安卓 |运行你的第一个 Android 应用
  • REST API(介绍)
  • Android 中的排球库

印度政府已经开始了印度最大的疫苗接种活动,为人们接种疫苗以对抗 COVID-19 病毒。由于印度有很多疫苗接种中心进行疫苗接种,因此要检查印度不同中心的不同疫苗接种情况。我们将构建一个简单的应用程序来获取有关印度疫苗接种中心的详细信息。

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

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在该应用程序中我们将从该位置的 Pincode 获取疫苗接种中心的数据。在下面的视频中,我们将看到我们将在本文中构建的内容。请注意,我们将使用Kotlin语言来实现这个项目。

第 1 步:打开一个新项目

  • 打开一个新项目只需单击左上角的文件选项。
  • 然后单击新建并使用您想要的任何名称打开一个新项目。
  • 现在我们将使用 Kotlin 语言处理 Empty Activity。保持所有其他选项不变。
  • 您可以根据自己的选择更改项目的名称
  • 默认情况下,会有两个文件activity_main.xml和MainActivity。Java。

或者要在 Android Studio 中创建新项目,请参阅如何在 Android Studio中创建/启动新项目

第 2 步:在进入编码部分之前,您必须先做一些预任务

转到app > res > values > colors.xml部分并为您的应用设置颜色。

XML


    #0F9D58
    #0F9D58
    #0F9D58
    #FF03DAC5
    #FF018786
    #FF000000
    #FFFFFFFF


XML


XML


  
    
    
  
    
    


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
)


XML


  
    
  
        
        
  
        
        
  
        
        
  
        
  
            
            
  
            
            
        
  
        
              
            
            
              
            
            
  
        
          
    
      


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) :
        RecyclerView.Adapter() {
  
    // 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 avalabilityTV: TextView = itemView.findViewById(R.id.idTVAvaliablity)
    }
  
    // below method is for on Create Vew 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.avalabilityTV.text = "Availability : " + currentItem.availableCapacity.toString()
    }
}


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
  
    // 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()
          
        // 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).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 avaliableCapacity: 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,
                                    avaliableCapacity
                            )
                            // 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)
    }
}


第 3 步:在 build.gradle 文件中为 Volley 添加依赖项

转到Gradle Scripts > build.gradle (Module: app)部分并导入以下依赖项,然后在上面的弹出窗口中单击“立即同步”。我们在这个项目中使用了 Volley 库。

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

第 4 步:在 AndroidManifest.xml 文件中添加 Internet 权限

导航到应用程序 > AndroidManifest.xml文件并在其中添加以下代码行。

XML



步骤 5:使用 activity_main.xml 文件

导航到app > res > layout > activity_main.xml并将以下代码添加到该文件中。下面是activity_main.xml文件的代码。

XML



  
    
    
  
    
    

第 6 步:创建一个新的 Kotlin 文件来存储我们的数据

我们必须将数据存储在模态类中,因为我们将创建一个新的 Kotlin 类文件。用于创建此文件。导航到应用程序 > Java > 您应用程序的包名称 > 右键单击它 > 新建 > Kotlin 文件/类选项,然后选择类并将您的文件命名为 CenterRvModal 并将以下代码添加到其中。代码中添加了注释,以便更详细地了解。

科特林

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
)

第 7 步:为我们的 RecyclerView 项创建一个新的布局文件

导航到app >res > layout > 右键单击它 > New > Layout file并将其命名为center_rv_item并向其添加以下代码。代码中添加了注释,以便更详细地了解。下面的布局文件可用于显示我们 RecyclerView 的每个项目。

XML



  
    
  
        
        
  
        
        
  
        
        
  
        
  
            
            
  
            
            
        
  
        
              
            
            
              
            
            
  
        
          
    
      

第 8 步:为我们的 Adapter 类创建一个新的 Kotlin 文件

现在为我们的 Recycler View 的每个项目设置数据。我们必须创建一个新的适配器类来为我们的 Recycler View 的每个项目设置数据。要创建新的 Kotlin 文件,请导航到应用程序 > Java > 您应用程序的包名称 > 右键单击它 > 新建 > Kotlin 文件/类并将其命名为CenterRVAdapter并将以下代码添加到其中。代码中添加了注释,以便更详细地了解。

科特林

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) :
        RecyclerView.Adapter() {
  
    // 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 avalabilityTV: TextView = itemView.findViewById(R.id.idTVAvaliablity)
    }
  
    // below method is for on Create Vew 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.avalabilityTV.text = "Availability : " + currentItem.availableCapacity.toString()
    }
}

第 9 步:使用 MainActivity.kt 文件。

导航到应用程序 > Java > 您应用程序的包名称 > MainActivity.kt文件并将以下代码添加到其中。代码中添加了注释,以便更详细地了解。

科特林

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
  
    // 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()
          
        // 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).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 avaliableCapacity: 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,
                                    avaliableCapacity
                            )
                            // 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)
    }
}

现在运行您的应用程序并查看应用程序的输出

输出:

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!