-1

I am trying to read all the users from my firebase realtime database and storing them in a database class, reading the users from the database works as expected however when i try to access the users from outside the class it returns an empty list. This is my database class

class Database {

private val database = FirebaseDatabase.getInstance();
var users = mutableListOf<User>()

init {
    val valueEventListener = object : ValueEventListener {
        override fun onDataChange(data: DataSnapshot) {
            if (data.exists()){
                for (child in data.children) {
                    val user = child.getValue(User::class.java)
                    users.add(user!!)
                }
            }
        }

        override fun onCancelled(data: DatabaseError) {
            println("Error occurred while reading users data")
        }
    }
    database.getReference("Users").addValueEventListener(valueEventListener)
}


fun writePerson(user:User) {
    val users = database.getReference("Users")
    users.child(user.firstname).setValue(user)
}

this is where i try to access the users from my database class

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    val database = Database()

    val rafael = User("Rafael","Backx");
    rafael.addPhoneNumber("0123456789")
    database.writePerson(rafael)
    val rafael2 = User("Rafael2","Backx");
    rafael2.addPhoneNumber("012345678910")
    database.writePerson(rafael2)

    val users = database.users;
    println(users.size)
    for (child in users){
        println(child)
    }
}

This is my first time using kotlin, android studio and firebase.

Thanks in advance

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Rafael
  • 83
  • 3
  • 10
  • Firebase API is asynchronous. So please check **[this](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method/47853774)** out. – Alex Mamo Sep 26 '20 at 15:25

1 Answers1

0

Firebase queries are asynchronous and do not complete immediately after you call addValueEventListener. Your code is assuming that the Database class gets populated immediately, but it does not. You can add some logging to see for yourself the order in which your code actually executes.

It's not particularly good design to use Firebase as you are now in the constructor of a class. If you're interested in doing things the way Google currently recommends, you might want to look into MVVM architecture. It's a lot more work, but it's the right way to handle asynchronous programming in an Android app.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441