'firestore read data adding hashmap get data when added

enter image description here

enter image description here

when the user presses the button onlick ,read data and add hashmap When completed I want to read with getfirestore2() method

data to come comment1 comment2 comment3 comment4

but incoming data with getfirestore2() method comment 4

my using method failed and not safe because I use delay

I how to fix codes?

my codes

    binding.AllAskedBtn.setOnClickListener {
        a1hliste.clear()
        a2hliste.clear()
        a3hliste.clear()
        a4hliste.clear()

         fun getfirestore2(){
            println("listedekiler A1 "+a1hliste)
            println("listedekiler A2 "+a2hliste)
            println("listedekiler A3 "+a3hliste)
            println("listedekiler A4 "+a4hliste)
            println("\n veri 2 db size "+dbsize)
             var sayi=0


             var g1=a1hliste.getValue(sayi).toString()
             var g2=a2hliste.getValue(sayi).toString()
             var g3=a3hliste.getValue(sayi).toString()
             var g4=a4hliste.getValue(sayi).toString()

                for (a in 0..dbsize-1){
                    db.collection(g1).document(g2).collection(g3).document(g4).addSnapshotListener { task,e->
                        var veri= task!!.get("comment") as String
                        println("This is the data from "+veri)
                    }
                }

                }


       db.collection("users").document(uuid).collection("Questions").orderBy("date",Query.Direction.DESCENDING).addSnapshotListener{ result, e->
           var veri=result!!.documents
           var verisize=result!!.documents.size
           dbsize=0
           for (a in veri){
               var dersler=a.get("FBDersler") as String
               var konular=a.get("FBKonular") as String
               var sinavturu=a.get("sinavturu") as String
               var QuestionUİD=a.get("QuestionUİD") as String


               a1hliste.put(dbsize,sinavturu.toString())
               a2hliste.put(dbsize,dersler.toString())
               a3hliste.put(dbsize,konular.toString())
               a4hliste.put(dbsize,QuestionUİD.toString())
               dbsize+=1

               GlobalScope.launch {
                   delay(2000L)
                   if (dbsize==verisize){
                       getfirestore2()
                   }
               }
           }
           println("db size "+dbsize)
       }





    }


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source