How to fix Runtime error while downloading file on android using Kotlin?

134 Views Asked by At

I am getting Runtime error while downloading file using Kotlin in android here in this code i am using thread and if i don't use it then app is crashing and I don't know why i am getting this error well I am new at Kotlin so sorry for any trouble, and also I am trying to make extension here for mit app inventor and i am new at this also ....

I use a SimpleFunction annotation to create a simple function block that will run another function ( download function ) here is SimpleFunction's code :

`

@SimpleFunction(description = "Simple download block")
fun simpleDownload(url: String, path: String) {
    val paths = if (path.endsWith("/")){
        "${path}${getFileName(url)}"
    }else{
        "${path}/${getFileName(url)}"
    }
    thread(
        start = true,
        isDaemon = true
    ){
    download(url, path)
    }
}

Here I use thread but it is crashing the application but when i don't use threading then i am getting Runtime error without any other data but i am able to create the file but don't able to save the stream content here is download function code ( Here getFileName function help to get filename from url )

`

fun download(link: String, path: String): Long {

    val url = URL(link)

    val connection = url.openConnection()

    connection.connect()

    url.openStream().use { input ->

        FileOutputStream(File(path)).use { output ->

            val buffer = ByteArray(DEFAULT_BUFFER_SIZE)

            var bytesRead = input.read(buffer)

            var bytesCopied = 0L

            while (bytesRead >= 0) {

                output.write(buffer, 0, bytesRead)

                bytesCopied += bytesRead

                bytesRead = input.read(buffer)

            }

            return bytesCopied

        }

    }

}

Well i can use Download Manager which is already available and its easy to download file from there but I don't want because it did't support some features which i needs so please help me to fix this issue :-(

2

There are 2 best solutions below

2
Taifun On

The App Inventor development environment currently does not support Kotlin. Use Java instead. See also the App Inventor Extensions document. Alternatively use the Rush development environment, which also supports Kotlin.

And for creating extensions please follow the naming conventions for extension developers.

0
Negar Dolat On

The App Inventor development environment currently does not support Kotlin. Use Java instead. See also the App Inventor Extensions document. Alternatively use the Rush development environment, which also supports Kotlin.

And for creating extensions please follow the naming conventions for extension developers.