首页 > 解决方案 > 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"
    }
}

可能出了什么问题?

标签: androidkotlin

解决方案


推荐阅读