【问题标题】:How to read a CSV file from a downloadable link in Android如何从 Android 中的可下载链接读取 CSV 文件
【发布时间】:2021-09-04 20:23:23
【问题描述】:

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

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

如果您单击该链接,它将下载一个 CSV 文件。

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

怎么做?

【问题讨论】:

标签: java android csv kotlin csvreader


【解决方案1】:

我发现这个 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()

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多