Search code examples
androidsqlitekotlinanko

Anko's execute the sqlite request but don't execute the next lines


I want to make a request on my internal database on Android but when my request Anko is done, the lines present in the UiThread are not done immediately.

To explain what happens, the line "Log.d" is execute before the UiThread

Can you help me?

for(i in 0 until jsonArrayM.length()) {
        val json = jsonArrayM.getJSONObject(i)
        doAsync {
            val carteByName = bdd.getDatasByName(json.get("role").toString())
            uiThread {
                json.put("id", carteByName[0].id)
                json.put("image", carteByName[0].imageCarte)
                json.put("nuit1", carteByName[0].premiereNuit)
                json.put("posNuit1", carteByName[0].positionPremiereNuit)
                json.put("autresNuits", carteByName[0].nuitSuivante)
                json.put("posAutresNuits", carteByName[0].positionNuitSuivante)
            }
        }
        jsonArray.put(json)
    }
    Log.d("Verif", jsonArray.toString())

Solution

  • The block inside doAsync is done asynchronously in a background thread, and the block inside uiThread is done only at the end of your async block (but on the UI/Main thread).
    The Log, on the other hand, is executed synchronously after the loop.
    So it is expected that the code inside the async block is executed after the synchronous code.