【发布时间】:2021-08-11 02:04:27
【问题描述】:
在这个应用程序中,我使用 HttpURLConnection 下载 Feed RSS“来自 XML 链接”,然后对其进行解析并查看到 listview,但是在我运行应用程序后,我得到了空的 listview
代码
private fun downloadXML(urlPath: String? ): String {
val xmlResult = StringBuilder()
GlobalScope.launch(Dispatchers.IO) {
kotlin.runCatching {
try {
Log.d(TAG,"Dispatchers.IO Called")
val url = URL(urlPath)
val connection: HttpURLConnection = url.openConnection() as HttpURLConnection
val responseCode = connection.responseCode
Log.d(TAG, "DownloadXML: the response code is $responseCode")
connection.inputStream.buffered().reader().use { xmlResult.append(it.readText()) }
Log.e(TAG,"xmlResult: is ${xmlResult}")
}catch (ex:Exception){
when(ex){
is MalformedURLException -> ex.message.toString()
is IOException -> ex.message.toString()
is SecurityException -> ex.message.toString()
else -> ex.message.toString()
}
}
}
}
Log.e(TAG,xmlResult.toString()) //====> THIS CODEDOES NOT EXECUTED
return xmlResult.toString() // AND THIS
}
并像这样使用它
private var feedURL:String = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/topfreeapplications/limit=10/xml"
private var feedLimit = 10
private var feedCashedURL = "INVALIDAED"
private val STATE_URL = "feedURL"
private val STATE_LIMIT = "feedLimit"
private val parseApplication = ParseApplication()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
downloadURL(feedURL.format(feedLimit))
val feedAdapter = FeedAdapter(this,R.layout.list_record,parseApplication.application)
binding.listView.adapter = feedAdapter
Log.d(TAG,"onCreate called")
}
private fun downloadURL(feedURL: String) {
if(feedURL != feedCashedURL){
Log.d(TAG, "download URL starting AsyncTask")
val rssFeed = downloadXML(feedURL)
parseApplication.parse(rssFeed)
feedCashedURL = feedURL
Log.d(TAG, "downloadURL done")
}else{
Log.d(TAG, "downloadURL URL not changed")
}
}
看起来这两行没有执行,因为即使我得到响应代码 200 和 xmlResult 打印但仅在 GlobalScope.launch 块内,我在结果中什么也没得到,所以如何从 Coroutine 块获取这个返回结果?
Log.e(TAG,xmlResult.toString())
return xmlResult.toString()
【问题讨论】:
标签: android kotlin networking return kotlin-coroutines