Kotlin Android Studio App在AsyncTask类上不断崩溃

时间:2018-06-09 21:33:48

标签: android kotlin

我试图下载一个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"
    }
}

可能出现什么问题?

0 个答案:

没有答案