【问题标题】:Make several tasks one after the other in a loop在一个循环中一个接一个地完成多个任务
【发布时间】:2018-10-27 16:09:30
【问题描述】:

我有对象数组, 我想为这个数组的每个对象创建一个 pdf。为此,我使用了一个循环,但问题是它为我创建了最后一个的 PDF 文件。

我想我知道为什么,因为任务没有时间完成它继续下一个。

我想在创建 pdf 文件之前停止循环,然后继续下一次迭代...

每次迭代我都想停止循环以腾出时间来创建 pdf 文件

这是我的代码:

for (i in 0 until multipleInvoice!!.size) {

            receiveUser = MainActivity.users.find { it.codeZ == multipleInvoice!![i].customerCodeZ }
            products = multipleInvoice!![i].retrieveInvoice(this)
            receiveInvoice = multipleInvoice!![i]

            doAsync {
                // Long background task
                progressBar.setVisible()
                htmlContent = renderHTML()

                uiThread {
                    //webViewInitializer(htmlContent)
                    doAsync {
                        htmlToPDF(htmlContent) //Is function create PDF file on the phone!!!
                        //Here I want to stop the loop until the file is created 
                        // (by the function of the line above). As soon as the file is created, we take the loop 
                    }
                    progressBar.setGone()
                }
            }
        }

【问题讨论】:

    标签: android asynchronous task


    【解决方案1】:

    你不能使用任何循环来实现你想要的。有一种方法可以使用递归执行您想要的操作。当您有多个发票时,调用第 0 个位置的此函数以呈现 PDF。

    if(multipleInvoice?:0 >0)    
      renderInvoice(0)
    
    
    fun renderInvoice(i:Int) {
    
            receiveUser = MainActivity.users.find { it.codeZ == multipleInvoice!![i].customerCodeZ }
            products = multipleInvoice!![i].retrieveInvoice(this)
            receiveInvoice = multipleInvoice!![i]
    
            doAsync {
                // Long background task
                progressBar.setVisible()
                htmlContent = renderHTML()
    
                uiThread {
                    //webViewInitializer(htmlContent)
                    doAsync {
                        htmlToPDF(htmlContent) //Is function create PDF file on the phone!!!
                        //Here I want to stop the loop until the file is created 
                        // (by the function of the line above). As soon as the file is created, we take the loop 
                       if(i< multipleInvoice!!.size)
                         renderInvoice(++i)
                    }
                    progressBar.setGone()
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多