0

In my activity I have this if that has the value of the reference to query the DB

reference  = if (valor == 1){
            ConversationsAdapter.teste.child("messages")
        }else{
            MainActivity.usersChatReference.child("messages")
        }

The problem is, when I use that reference variable as reference to query my DB, I get an error saying "lateinit property reference has not been initialized". How can I make sure that the code above runs before this query code:

reference.addChildEventListener(object : ChildEventListener{
            override fun onCancelled(p0: DatabaseError) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onChildMoved(p0: DataSnapshot, p1: String?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onChildChanged(p0: DataSnapshot, p1: String?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onChildAdded(p0: DataSnapshot, p1: String?) {
                teste()
            }

            override fun onChildRemoved(p0: DataSnapshot) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

        })
André Nogueira
  • 3,363
  • 3
  • 10
  • 16

1 Answers1

0

From a quick search it seems you can (and need to) safeguard your code against possibly not initializing the variable with:

if (::reference.isInitialized) {
  reference.addChildEventListener(object : ChildEventListener{
  ...

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807