There are many android applications which are available in the market which provide real-time cricket score updates easily at your fingertips. This application provides real-time updates for different cricket matches being played across the world. In this article, we will be building a simple application in which we will be displaying live cricket scores of various matches being played across the world. A sample video is given below to get an idea about what we are going to do in this article.
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. Note that select Kotlin as the programming language.
Step 2: Add dependency to use volley for json parsing in android
Navigate to app>Gradle Scripts>build.gradle file and add the below dependency to it in the dependencies section.
implementation 'com.android.volley:volley:1.2.1'
After adding the above dependency simply sync your project to install to it.
Step 3: Create a Card Layout for Recycler View Card Items
Go to the app > res > layout> right-click > New >Layout Resource File and name the file as match_rv_item. In this file, all XML code related to card items in the RecyclerView is written. Below is the code for the match_rv_item.xml file.
<? xml version = "1.0" encoding = "utf-8" ?>
< androidx.cardview.widget.CardView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_gravity = "center"
android:layout_margin = "5dp"
android:padding = "4dp"
app:cardCornerRadius = "5dp" >
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content" >
<!--text view for displaying match title-->
< TextView
android:id = "@+id/idTVMatchTitle"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginStart = "6dp"
android:layout_marginTop = "3dp"
android:layout_marginEnd = "3dp"
android:layout_marginBottom = "3dp"
android:padding = "4dp"
android:text = "Match Title"
android:textColor = "@color/black"
android:textSize = "12sp" />
< LinearLayout
android:id = "@+id/idLLT1"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@id/idTVMatchTitle"
android:orientation = "horizontal"
android:padding = "2dp"
android:weightSum = "2" >
<!--text view for displaying match team 1-->
< TextView
android:id = "@+id/idTvTeam1"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:layout_margin = "3dp"
android:layout_weight = "1"
android:padding = "4dp"
android:text = "Team 1"
android:textColor = "@color/black"
android:textSize = "18sp"
android:textStyle = "normal" />
<!--text view for displaying match team 1 score-->
< TextView
android:id = "@+id/idTvScore1"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:layout_margin = "3dp"
android:layout_weight = "1"
android:padding = "4dp"
android:text = "Team 1 score"
android:textColor = "@color/black"
android:textSize = "18sp"
android:textStyle = "normal" />
</ LinearLayout >
< LinearLayout
android:id = "@+id/idLLT2"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@id/idLLT1"
android:orientation = "horizontal"
android:padding = "2dp"
android:weightSum = "2" >
<!--text view for displaying match team2-->
< TextView
android:id = "@+id/idTvTeam2"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:layout_margin = "3dp"
android:layout_weight = "1"
android:padding = "4dp"
android:text = "Team 2"
android:textColor = "@color/black"
android:textSize = "18sp"
android:textStyle = "normal" />
<!--text view for displaying match team score 2-->
< TextView
android:id = "@+id/idTvScore2"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:layout_margin = "3dp"
android:layout_weight = "1"
android:padding = "4dp"
android:text = "Team 2 score"
android:textColor = "@color/black"
android:textSize = "18sp"
android:textStyle = "normal" />
</ LinearLayout >
<!--text view for displaying match status-->
< TextView
android:id = "@+id/idTVMatchStatus"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@id/idLLT2"
android:layout_marginStart = "4dp"
android:layout_marginTop = "4dp"
android:layout_marginEnd = "4dp"
android:layout_marginBottom = "4dp"
android:padding = "5dp"
android:text = "Match status"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "bold" />
</ RelativeLayout >
</ androidx.cardview.widget.CardView >
|
Step 4: 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. Comments are added inside the code to understand the code in more detail.
<? xml version = "1.0" encoding = "utf-8" ?>
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MainActivity" >
<!--adding text view for displaying heading-->
< TextView
android:id = "@+id/idTVHeading"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "10dp"
android:padding = "10dp"
android:text = "Matches"
android:textColor = "@color/black"
android:textSize = "20sp"
android:textStyle = "bold" />
<!--adding progress bar on below line-->
< ProgressBar
android:id = "@+id/idPBLoading"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerInParent = "true"
android:visibility = "visible" />
<!--adding recycler view to display list of matches-->
< androidx.recyclerview.widget.RecyclerView
android:id = "@+id/idRVMatches"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:layout_below = "@id/idTVHeading"
android:orientation = "vertical"
android:visibility = "gone"
app:layoutManager = "androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem = "@layout/match_rv_item" />
</ RelativeLayout >
|
Step 5: Create a Modal class for score data and match data
Go to the app > java > Right-Click on your app’s package name > New > Kotlin Class and name the file as Score. This class will contain the scores for the individual team for that specific match. Below is the code for it. Comments are added to it to get to know it in detail.
package com.example.cricscore
data class Score(
// creating variables for runs,
// wickets, overs and innings.
var runs: Int,
var wickets: Int,
var overs: Int,
var innings: String,)
|
Now Go to the app > java > Right-Click on your app’s package name > New > Kotlin Class and name the file as MatchesRVModal. This class will contain the details of all the matches.
package com.example.cricscore
data class MatchesRVModal(
// on below line creating variables
var matchID: String,
var matchName: String,
var matchType: String,
var status: String,
var venue: String,
var date: String,
var teams: List<String>,
var scores: List<Score>
)
|
Step 6: Create a new activity to display in detail score of a specific match
Navigate to app>java>your app’s package name> Right-click on it>New>Activity>Empty Activity and specify a name to it as MatchScoreActivity.
Step 7: Working with activity_match_score.xml file
Navigate to app>res>layout>activity_match_score.xml and add the below code to it. Comments are added in the code to get to know it in detail.
<? xml version = "1.0" encoding = "utf-8" ?>
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".MatchScoreActivity" >
<!--adding progress bar on below line-->
< ProgressBar
android:id = "@+id/idPBLoading"
android:layout_width = "wrap_content"
android:layout_height = "wrap_content"
android:layout_centerInParent = "true" />
<!-- text view for match title-->
< TextView
android:id = "@+id/idTVMatchTitle"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_marginStart = "5dp"
android:layout_marginTop = "50dp"
android:layout_marginEnd = "5dp"
android:layout_marginBottom = "5dp"
android:padding = "4dp"
android:text = "Match Title"
android:textAlignment = "center"
android:textColor = "@color/black"
android:textSize = "20sp"
android:textStyle = "bold" />
< androidx.cardview.widget.CardView
android:id = "@+id/idCVMatchInfo"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@id/idTVMatchTitle"
android:layout_gravity = "center"
android:layout_marginLeft = "5dp"
android:layout_marginTop = "20dp"
android:layout_marginRight = "5dp"
android:layout_marginBottom = "5dp"
android:padding = "4dp"
app:cardCornerRadius = "5dp" >
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content" >
< LinearLayout
android:id = "@+id/idLLT1"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "horizontal"
android:padding = "2dp"
android:weightSum = "2" >
<!-- text view for team 1 title-->
< TextView
android:id = "@+id/idTvTeam1"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:layout_margin = "3dp"
android:layout_weight = "1"
android:padding = "4dp"
android:text = "Team 1"
android:textColor = "@color/black"
android:textSize = "18sp"
android:textStyle = "normal" />
<!-- text view for team 1 scores-->
< TextView
android:id = "@+id/idTvScore1"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:layout_margin = "3dp"
android:layout_weight = "1"
android:padding = "4dp"
android:text = "Team 1 score"
android:textColor = "@color/black"
android:textSize = "18sp"
android:textStyle = "normal" />
</ LinearLayout >
< LinearLayout
android:id = "@+id/idLLT2"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@id/idLLT1"
android:orientation = "horizontal"
android:padding = "2dp"
android:weightSum = "2" >
<!-- text view for team 2-->
< TextView
android:id = "@+id/idTvTeam2"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:layout_margin = "3dp"
android:layout_weight = "1"
android:padding = "4dp"
android:text = "Team 2"
android:textColor = "@color/black"
android:textSize = "18sp"
android:textStyle = "normal" />
<!-- text view for team 2 scores-->
< TextView
android:id = "@+id/idTvScore2"
android:layout_width = "0dp"
android:layout_height = "wrap_content"
android:layout_margin = "3dp"
android:layout_weight = "1"
android:padding = "4dp"
android:text = "Team 2 score"
android:textColor = "@color/black"
android:textSize = "18sp"
android:textStyle = "normal" />
</ LinearLayout >
<!-- text view for match status-->
< TextView
android:id = "@+id/idTVMatchStatus"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@id/idLLT2"
android:layout_marginStart = "4dp"
android:layout_marginTop = "4dp"
android:layout_marginEnd = "4dp"
android:layout_marginBottom = "4dp"
android:padding = "5dp"
android:text = "Match status"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "bold" />
</ RelativeLayout >
</ androidx.cardview.widget.CardView >
< TextView
android:id = "@+id/idTVInfo"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@id/idCVMatchInfo"
android:layout_marginStart = "5dp"
android:layout_marginTop = "20dp"
android:layout_marginEnd = "5dp"
android:layout_marginBottom = "5dp"
android:padding = "4dp"
android:text = "Match Info"
android:textAlignment = "center"
android:textColor = "@color/black"
android:textSize = "20sp"
android:textStyle = "bold" />
< androidx.cardview.widget.CardView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_below = "@id/idTVInfo"
android:layout_gravity = "center"
android:layout_margin = "5dp"
android:padding = "4dp"
app:cardCornerRadius = "5dp" >
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "vertical" >
< TextView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "2dp"
android:padding = "3dp"
android:text = "Match"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "bold" />
<!-- text view for match name-->
< TextView
android:id = "@+id/idTVMatchName"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "2dp"
android:padding = "3dp"
android:text = "Match Name"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "normal" />
< View
android:layout_width = "match_parent"
android:layout_height = "0.5dp"
android:background = "@color/black" />
< TextView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "2dp"
android:padding = "3dp"
android:text = "Date"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "bold" />
<!-- text view for match date-->
< TextView
android:id = "@+id/idTVMatchDate"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "2dp"
android:padding = "3dp"
android:text = "Match Date"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "normal" />
< View
android:layout_width = "match_parent"
android:layout_height = "0.5dp"
android:background = "@color/black" />
< TextView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "2dp"
android:padding = "3dp"
android:text = "Match Type"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "bold" />
<!-- text view for match type-->
< TextView
android:id = "@+id/idTVMatchType"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "2dp"
android:padding = "3dp"
android:text = "Match Type"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "normal" />
< View
android:layout_width = "match_parent"
android:layout_height = "0.5dp"
android:background = "@color/black" />
< TextView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "2dp"
android:padding = "3dp"
android:text = "Match Venue"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "bold" />
<!-- text view for match venue-->
< TextView
android:id = "@+id/idTVMatchVenue"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "2dp"
android:padding = "3dp"
android:text = "Match Venue"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "normal" />
< View
android:layout_width = "match_parent"
android:layout_height = "0.5dp"
android:background = "@color/black" />
<!-- text view for match toss-->
< TextView
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "2dp"
android:padding = "3dp"
android:text = "Toss"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "bold" />
< TextView
android:id = "@+id/idTVToss"
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_margin = "2dp"
android:padding = "3dp"
android:text = "Match Toss"
android:textColor = "@color/black"
android:textSize = "12sp"
android:textStyle = "normal" />
< View
android:layout_width = "match_parent"
android:layout_height = "0.5dp"
android:background = "@color/black" />
</ LinearLayout >
</ androidx.cardview.widget.CardView >
</ RelativeLayout >
|
Step 8: Create a new Kotlin class for the adapter
Navigate to the app.java>your app’s package name>Right click on it>New>Kotlin Class and name it as MatchesRVAdapter and add the below code to it. Comments are added inside the code to understand the code in more detail.
package com.example.cricscore
import android.content.Context
import android.content.Intent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
class MatchesRVAdapter( private val matchList: List<MatchesRVModal>, private val ctx: Context) :
RecyclerView.Adapter<MatchesRVAdapter.ViewHolder>() {
// on below line creating a view holder class.
class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
// on below line initializing variables with id.
val matchTitleTV: TextView = itemView.findViewById(R.id.idTVMatchTitle)
val team1TV: TextView = itemView.findViewById(R.id.idTvTeam1)
val teams2TV: TextView = itemView.findViewById(R.id.idTvTeam2)
val team1ScoreTV: TextView = itemView.findViewById(R.id.idTvScore1)
val team2ScoreTV: TextView = itemView.findViewById(R.id.idTvScore2)
val matchStatusTV: TextView = itemView.findViewById(R.id.idTVMatchStatus)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
// on below line inflating our layout file.
val view =
LayoutInflater.from(parent.context).inflate(R.layout.match_rv_item, parent, false )
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// on below line setting data to text view.
holder.matchTitleTV.text = matchList.get(position).matchName
holder.matchStatusTV.text = matchList.get(position).status
val teamsList: List<String> = matchList.get(position).teams
holder.team1TV.text = matchList.get(position).teams.get( 0 )
holder.teams2TV.text = matchList.get(position).teams.get( 1 )
// on below line adding click listener for recycler view item.
holder.itemView.setOnClickListener {
// starting a new intent on below line.
val intent = Intent(ctx, MatchScoreActivity:: class .java)
intent.putExtra( "matchID" , matchList.get(position).matchID)
ctx.startActivity(intent)
}
val scoreList: List<Score> = matchList.get(position).scores
holder.team1ScoreTV.text =
matchList.get(position).scores.get( 0 ).runs.toString() + "/" + matchList.get(position).scores.get(
0
).wickets + "(" + matchList.get(position).scores.get( 0 ).overs + ")"
if (matchList.get(position).scores.size == 2 ) {
holder.team2ScoreTV.text =
matchList.get(position).scores.get( 1 ).runs.toString() + "/" + matchList.get(position).scores.get(
1
).wickets + "(" + matchList.get(position).scores.get( 1 ).overs + ")"
}
}
override fun getItemCount(): Int {
// returning size of list
return matchList.size
}
} |
Step 9: Generating the API key
Navigate to the below URL and simply sign up with your email address and password. You will get to see your API key along with API Url which we can use within our application to display cricket-related data.
https://cricketdata.org/
Step 10: Working with MatchScoreActivity.kt file.
Navigate to app>java>your app’s package name>MatchScoreActivity.kt file and add the below code to it. Comments are added inside the code to understand the code in more detail.
package com.example.cricscore
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import org.json.JSONArray
import org.json.JSONObject
class MatchScoreActivity : AppCompatActivity() {
// on below line creating variables for text views.
lateinit var matchTitleTV: TextView
lateinit var matchNameTV: TextView
lateinit var team1TV: TextView
lateinit var team2TV: TextView
lateinit var team1ScoreTV: TextView
lateinit var team2ScoreTV: TextView
lateinit var matchStatusTV: TextView
lateinit var matchDateTV: TextView
lateinit var matchTypeTV: TextView
lateinit var matchVenueTV: TextView
lateinit var matchTossTV: TextView
lateinit var loadingPB: ProgressBar
// on below line specifying refresh time for score.
val period: Long = 5000
// on below line specifying api url
var apiURL: String =
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_match_score)
// on below line initializing all variables.
matchTitleTV = findViewById(R.id.idTVMatchTitle)
matchNameTV = findViewById(R.id.idTVMatchName)
team1TV = findViewById(R.id.idTvTeam1)
team2TV = findViewById(R.id.idTvTeam2)
team1ScoreTV = findViewById(R.id.idTvScore1)
team2ScoreTV = findViewById(R.id.idTvScore2)
matchStatusTV = findViewById(R.id.idTVMatchStatus)
matchDateTV = findViewById(R.id.idTVMatchDate)
matchTypeTV = findViewById(R.id.idTVMatchType)
matchVenueTV = findViewById(R.id.idTVMatchVenue)
matchTossTV = findViewById(R.id.idTVToss)
loadingPB = findViewById(R.id.idPBLoading)
// on below line getting match id through intent.
val matchID = intent.getStringExtra( "matchID" )
// on below line specifying timer to
// make api call after every 5 seconds.
Timer().schedule(object : TimerTask() {
@Override
fun run() {
// on below line calling get score
// data after specific time interval
getScoreData()
}
}, 0 , period)
}
private fun getScoreData() {
val queue: RequestQueue = Volley.newRequestQueue(applicationContext)
// on below line we are creating a variable for request
// and initializing it with json object request
val request = JsonObjectRequest(Request.Method.GET, apiURL + matchID, null , { response ->
// on below line we are adding a try catch block.
try {
// on below line we are getting data from our response
// and setting it in variables.
val dataObj: JSONObject = response.getJSONObject( "data" )
// on below line changing visibility of progress bar.
loadingPB.visibility = View.GONE
// on below line initializing list.
val teamsList = ArrayList<String>()
val scoreCardList = ArrayList<Score>()
val matchesScoresRVList = ArrayList<MatchesRVModal>()
// on below line getting data from api.
var matchName: String = dataObj.getString( "name" )
var matchType: String = dataObj.getString( "matchType" )
var matchstatus: String = dataObj.getString( "status" )
var matchvenue: String = dataObj.getString( "venue" )
var matchdate: String = dataObj.getString( "date" )
var teamsArray: JSONArray = dataObj.getJSONArray( "teams" )
for (j in 0 until teamsArray.length()) {
teamsList.add(teamsArray.getString(j))
}
var scoreArray: JSONArray = dataObj.getJSONArray( "score" )
for (k in 0 until scoreArray.length()) {
var scoreObj = scoreArray.getJSONObject(k)
var runs = scoreObj.getInt( "r" )
var overs = scoreObj.getInt( "o" )
var wickets = scoreObj.getInt( "w" )
var innings = scoreObj.getString( "inning" )
scoreCardList.add(Score(runs, overs, wickets, innings))
}
// on below line setting data
// for our text views.
matchTitleTV.text = matchName
matchNameTV.text = matchName
matchTypeTV.text = matchType
matchStatusTV.text = matchstatus
matchVenueTV.text = matchvenue
matchDateTV.text = matchdate
team1TV.text = teamsList.get( 0 )
team2TV.text = teamsList.get( 1 )
team1ScoreTV.text =
scoreCardList.get( 0 ).runs.toString() + "/" + scoreCardList.get(
0
).wickets + "(" + scoreCardList.get( 0 ).overs + ")"
team2ScoreTV.text =
scoreCardList.get( 1 ).runs.toString() + "/" + scoreCardList.get(
1
).wickets + "(" + scoreCardList.get( 1 ).overs + ")"
Log.e( "TAG" , "Data form api is : " + matchesScoresRVList)
} catch (e: Exception) {
// on below line we are
// handling our exception.
e.printStackTrace()
}
}, { error ->
// this method is called when we get
// any error while fetching data from our API
// in this case we are simply displaying a toast message.
Toast.makeText( this @MatchScoreActivity , "Fail to get response" , Toast.LENGTH_SHORT)
.show()
})
// at last we are adding
// our request to our queue.
queue.add(request)
}
} |
Step 11: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
package com.example.cricscore
import android.os.Bundle
import android.util.Log
import android.view.View
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.RequestQueue
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.Volley
import org.json.JSONArray
import org.json.JSONObject
class MainActivity : AppCompatActivity() {
// on below line creating variable for
// api url, recycler view and progress bar.
var apiURL: String =
lateinit var matchRV: RecyclerView
lateinit var loadingPB: ProgressBar
// on below line specifying
// refresh time for score.
val period: Long = 5000
override fun onCreate(savedInstanceState: Bundle?) {
super .onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// initializing variables on below line.
matchRV = findViewById(R.id.idRVMatches)
loadingPB = findViewById(R.id.idPBLoading)
// on below line specifying timer to make
// api call after every 5 seconds.
Timer().schedule(object : TimerTask() {
@Override
fun run() {
// on below line calling get matches
// data after specific time interval
getMatchesData()
}
}, 0 , period)
}
private fun getMatchesData() {
val queue: RequestQueue = Volley.newRequestQueue(applicationContext)
// on below line we are creating a variable for request
// and initializing it with json object request
val request = JsonObjectRequest(Request.Method.GET, apiURL, null , { response ->
// on below line we are adding a try catch block.
try {
// on below line we are getting
// data from our response
// and setting it in variables.
val dataArray: JSONArray = response.getJSONArray( "data" )
loadingPB.visibility = View.GONE
matchRV.visibility = View.VISIBLE
val matchesScoresRVList = ArrayList<MatchesRVModal>()
for (i in 0 until dataArray.length()) {
var dataObj = dataArray.getJSONObject(i)
var matchName: String = dataObj.getString( "name" )
var matchType: String = dataObj.getString( "matchType" )
var matchstatus: String = dataObj.getString( "status" )
var matchvenue: String = dataObj.getString( "venue" )
var matchdate: String = dataObj.getString( "date" )
var matchID: String = dataObj.getString( "id" )
val teamsList = ArrayList<String>()
val scoreCardList = ArrayList<Score>()
var teamsArray: JSONArray = dataObj.getJSONArray( "teams" )
for (j in 0 until teamsArray.length()) {
teamsList.add(teamsArray.getString(j))
}
Log.e( "TAG" , "TEams list is : " + teamsList)
var scoreArray: JSONArray = dataObj.getJSONArray( "score" )
for (k in 0 until scoreArray.length()) {
var scoreObj = scoreArray.getJSONObject(k)
var runs = scoreObj.getInt( "r" )
var overs = scoreObj.getInt( "o" )
var wickets = scoreObj.getInt( "w" )
var innings = scoreObj.getString( "inning" )
scoreCardList.add(Score(runs, wickets, overs, innings))
}
Log.e( "TAG" , "Score list is : " + scoreCardList)
matchesScoresRVList.add(
MatchesRVModal(
matchID,
matchName,
matchType,
matchstatus,
matchvenue,
matchdate,
teamsList,
scoreCardList
)
)
Log.e( "TAG" , "Data form api is : " + matchesScoresRVList)
}
val matchRVAdapter = MatchesRVAdapter(matchesScoresRVList, this )
matchRV.adapter = matchRVAdapter
} catch (e: Exception) {
// on below line we are
// handling our exception.
e.printStackTrace()
}
}, { error ->
// this method is called when we get
// any error while fetching data from our API
// 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 application to see the output of it.