how to show progress while uploading files
# android
s
how to show progress while uploading files
stackoverflow 3
s
Use async tasks
d
@sanket AsyncTasks are deprecated. @san How are you uploading files?
s
i used retrofit lib to upload files as multipart
now i want to show the progress ,so how to implement that
d
You can create a custom
RequestBody
that will emit progress. Here’s how I did this in my project:
Copy code
class ProgressEmittingRequestBody(
    private val mediaType: String,
    private val file: File,
    private val onProgressUpdate: (Int) -> Unit
) : RequestBody() {

    override fun contentType(): MediaType? = MediaType.parse(mediaType)

    override fun contentLength(): Long = file.length()

    override fun writeTo(sink: BufferedSink) {

        val inputStream = FileInputStream(file)
        val buffer = ByteArray(BUFFER_SIZE)
        var uploaded: Long = 0
        val fileSize = file.length()

        try {
            while (true) {

                val read = inputStream.read(buffer)
                if (read == -1) break

                uploaded += read
                sink.write(buffer, 0, read)

                val progress = (((uploaded / fileSize.toDouble())) * 100).toInt()
                onProgressUpdate(progress)
            }
        } catch (e: Exception) {
            Timber.e(e)
        } finally {
            inputStream.close()
        }
    }

    companion object {
        const val BUFFER_SIZE = 1024
    }
}
s
ok
how to show progress if i upload multiple files
d
In that case you’ll observe each progress independently. What’s your concern exactly?
s
in this code your passing file as a parameter but I'm having uri only
so how to do with the uri or how can i get the file from uri
204 Views