AsyncTask in Android with Kotlin

前端 未结 10 1515
离开以前
离开以前 2020-12-13 12:31

How to make an API call in Android with Kotlin?

I have heard of Anko . But I want to use methods provided by Kotlin like in Android we have Asynctask for background

10条回答
  •  北海茫月
    2020-12-13 13:00

    if in the case you want to do it without using Anko and the correct way is to use the following way

    open class PromotionAsyncTask : AsyncTask>() {
    
    private lateinit var out: FileOutputStream
    private lateinit var bitmap: Bitmap
    private lateinit var directory: File
    private var listPromotion: MutableList = mutableListOf()
    
    override fun doInBackground(vararg params: JsonArray?): MutableList {
    
        directory = Environment.getExternalStoragePublicDirectory("Tambo")
    
        if (!directory.exists()) {
            directory.mkdirs()
        }
    
        for (x in listFilesPromotion(params[0]!!)) {
            bitmap = BitmapFactory.decodeStream(URL(x.url).content as InputStream)
            out = FileOutputStream(File(directory, "${x.name}"))
    
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)
            out.flush()
            out.close()
    
            listPromotion.add(File(directory, "${x.name}").toString())
        }
    
        return listPromotion
    }
    
    private fun listFilesPromotion(jsonArray: JsonArray): MutableList {
        var listString = mutableListOf()
    
        for (x in jsonArray) {
            listString.add(Promotion(x.asJsonObject.get("photo")
                    .asString.replace("files/promos/", "")
                    , "https://tambomas.pe/${x.asJsonObject.get("photo").asString}"))
        }
    
        return listString}
    }
    

    and the way to execute it is as follows

    promotionAsyncTask = object : PromotionAsyncTask() {
                        override fun onPostExecute(result: MutableList?) {
                            super.onPostExecute(result)
                            listFile = result!!
    
                            contentLayout.visibility = View.VISIBLE
                            progressLottie.visibility = View.GONE
                        }
                    }
                    promotionAsyncTask.execute(response!!.body()!!.asJsonObject.get("promos").asJsonArray)
    

提交回复
热议问题