android - Kotlin Android Studio App 在 AsyncTask 类上不断崩溃
问题描述
我正在尝试下载一个 XML 文件,但应用程序在 Downloader 上不断崩溃(奇怪的是,它在崩溃之前又回到了 MainActiivty)。这是代码: 在 onCreate 中:
importButton.setOnClickListener {
downloadData()
}
后来在活动课上
fun downloadData() {
val cd = XMLDownloader()
cd.execute(sInf!!.getURLprefix(),sInf!!.getSetID().toString())
}
private inner class XMLDownloader : AsyncTask<String, Int, String>() {
override fun doInBackground(vararg params: String?): String {
try {
val url = URL(params[0]+params[1]+".xml")
val connection = url.openConnection()
connection.connect()
val lenghtOfFile = connection.contentLength
val isStream = url.openStream()
val testDirectory = File("$filesDir/XML")
if (!testDirectory.exists()) testDirectory.mkdir()
val fos = FileOutputStream("$testDirectory/"+params[1]+".xml")
val data = ByteArray( 1024)
var count = 0
var total: Long = 0
var progress = 0
count = isStream.read(data)
while (count != -1) {
total += count.toLong()
val progress_temp = total.toInt() * 100 / lenghtOfFile
if (progress_temp % 10 == 0 && progress != progress_temp) {
progress = progress_temp
}
fos.write(data, 0, count)
count = isStream.read(data)
}
isStream.close()
fos.close()
} catch (e: MalformedURLException) {
return "Malformed URL"
} catch (e: FileNotFoundException) {
return "File not found"
} catch (e: IOException) {
return "IOException"
}
return "success"
}
}
可能出了什么问题?
解决方案
推荐阅读
- go - *(*int)(nil) = 0 在 golang 中是什么意思?
- android - Android 通知图标在某些设备上为空白
- android - Android材质按钮采用颜色原色而不是颜色重音
- javascript - 如何根据条件更改进度条的颜色
- java - 将字符串中的连续数字值转换为数字格式
- ansible - Ansible items.key in when 条件
- android - 如何保存底部导航片段的状态 - 具有单个导航图的 Android 导航组件
- html - 搜索输入在展开时推送链接列表
- python - 如何绘制具有多个边缘属性的networkx图?
- c# - Fluent Ribbon 未在 Visual Studio 2019 中编译