Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

616
Views
Return string from Firebase addOnSuccessListener

I am programming the backend of a multiplayer game for a school project. I need to load a random document (more specifically a user's username) from a collection of users. That part works. Basically, I run into an issue where the username stays null ("") when I call the function, instead of the username that should be loaded with the docRef.get() function. Below is the code that I wrote, however I've found that it doesn't only happen with this function, but with all the ones that use the docRef.get() function.

Any help would be much appreciated, as I've been stuck on this issue for over a week. It's my first project in Kotlin/Firebase.

Thanks.

fun getRandomPlayerUsername() : String{

     var db = FirebaseFirestore.getInstance() // Loads Firebase functions

     var loadedPlayer:LoadedPlayer? = null

     val random = (0 until 3).random()

     val docRef = db.collection("users").orderBy("username").limit(3)

     var username:String = ""



     docRef.get().addOnSuccessListener { documentSnapshot ->

          val playerList: MutableList<out LoadedPlayer> = documentSnapshot.toObjects(LoadedPlayer()::class.java)

          loadedPlayer = playerList[random]

          username = loadedPlayer?.username.toString()
     }

     return username
}
over 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!