In the app, I'm currently making, I need to read a CSV file from a downloadable link and show its data.
For example, consider this link: https://api.covid19india.org/csv/latest/case_time_series.csv
If you click on the link, it'll download a CSV file.
So, what I want to do is, when the user opens the app, I want to access the data in this CSV link, parse it and show the data on the screen in a recycler view.
How to do that?
I found this Kotlin code as one of the way to get the data in CSV by using Volley's stringRequest
. In this case we get all the data as a string with rows being separated by \n
and data in a row being separated by commas(,
)
For this sample code, I'm accessing date from this URL: https://sample-videos.com/csv/Sample-Spreadsheet-10-rows.csv
val queue = Volley.newRequestQueue(this)
val url = "https://sample-videos.com/csv/Sample-Spreadsheet-10-rows.csv"
val stringRequest = StringRequest(
Request.Method.GET, url,
{ response ->
// Display the first 500 characters of the response string.
binding.csvDataTextView.text = "Response is: ${response.substring(0, 500)}"
val allLinesInResponse = response.substring(0)
var rowsData: List<String> = allLinesInResponse.split("\n")
Log.d("abc", "The Volley request worked")
},
{
Log.d("abc", "The Volley request didn't work!")
})
queue.add(stringRequest)
queue.start()
There may be other better ways, but this is one of those which work.