在进行多个改造调用时显示进度对话框

时间:2019-01-16 13:36:18

标签: android kotlin retrofit2

我想创建一个呼叫列表,以上传图片列表,在开始时显示进度对话框,然后在结束时将其关闭。 Howewer进度对话框永远不会显示。如果我评论progresRing.dismiss(),则会显示对话框,但稍后会出现。有没有比for循环更好的方法来进行多次调用?

        val progresRing = ProgressDialog(this@AddExtraPicturesActivity)
        progresRing.isIndeterminate = true
        progresRing.setTitle("Uploading pictures")
        progresRing.setMessage("Please wait")
        progresRing.setCancelable(false)

        progresRing.show()
        for (item in pictureList) {

            if(item.pictureFile != null) {
                val file = item.pictureFile

                if(file!!.exists()) {
                    var fileData = Base64.encodeToString(FileUtils.readFileToString(file).toByteArray(), Base64.DEFAULT)

                    val transactionId = UUID.randomUUID().toString()
                    val tokenId = ""

                    val jobDocument = JobDocument("Test", "", "", "PHONE_PICTURE", "jpg", "test.jpg", "", fileData)
                    val requestBody = UploadDocumentRequest("Test", jobDocument)

                    val service = RestAPI(this@AddExtraPicturesActivity)


                    val request = service.uploadDocument(authorization, transactionId, tokenId, requestBody)

                    request.enqueue(object :  Callback<UploadDocumentResponse> {
                        override fun onResponse(call: Call<UploadDocumentResponse>, response: Response<UploadDocumentResponse>) {
                            Timber.d( response.toString())
                        }

                        override fun onFailure(call: Call<UploadDocumentResponse>, t: Throwable) {
                            Timber.d(t.toString())

                        }
                    })
                }
            }
        }
        progresRing.dismiss()

1 个答案:

答案 0 :(得分:0)

实现此目标的最佳方法肯定是使用Reactive Programming,这样,当所有调用完成后就可以进行某种回调。

一种更简单的方法是计算您需要进行的呼叫总数并执行以下操作:

// find here the total of calls you need to make before the loop
totalCount = ??
var = 0

// and later, as retrofit requests are asynchronous, on the last upload the condition will be valid and the progress should dismiss
request.enqueue(object :  Callback<UploadDocumentResponse> {
                    override fun onResponse(call: Call<UploadDocumentResponse>, response: Response<UploadDocumentResponse>) {
                        Timber.d( response.toString())
                        var = var + 1
                        if(var == totalCount)
                            progresRing.dismiss()
                    }

                    override fun onFailure(call: Call<UploadDocumentResponse>, t: Throwable) {
                        Timber.d(t.toString())

                    }
                })