如何从 Android 中的可下载 link 中读取 CSV 文件

How to read a CSV file from a downloadable link in Android

在我目前正在制作的应用中,我需要从可下载的 link 中读取 CSV 文件并显示其数据。

例如,考虑这个 link:https://api.covid19india.org/csv/latest/case_time_series.csv

如果您点击 link,它会下载一个 CSV 文件。

所以,我想做的是,当用户打开应用程序时,我想访问此 CSV link 中的数据,对其进行解析并在回收站视图中的屏幕上显示数据。

怎么做?

我发现这个 Kotlin 代码是使用 Volley stringRequest 获取 CSV 数据的方法之一。在这种情况下,我们将所有数据作为字符串获取,其中行由 \n 分隔,一行中的数据由逗号分隔 (,)

对于此示例代码,我正在从 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()

可能还有其他更好的方法,但这是有效的方法之一。