1

I've got problem with using database values in app. I can't find way to use them in app.

auth = FirebaseAuth.getInstance()
        FirebaseUser = auth.getCurrentUser()!!

        val uid = auth.getUid()!!
        val fireBase = FirebaseDatabase.getInstance()
        userRef = fireBase.getReference("users")

        val ordersRef = userRef.child("$uid")
        val valueEventListener = object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val username = dataSnapshot.child("names").getValue(String::class.java)
                val lastname = dataSnapshot.child("lastname").getValue(String::class.java)
                Log.d("Data",lastname)
                Log.d("Data",username)
            }

            override fun onCancelled(databaseError: DatabaseError) {
                Log.d("Data", databaseError.getMessage()) //Don't ignore errors!
            }
        }
        ordersRef.addValueEventListener(valueEventListener)

This is the way to retrive data from firebase. I get it in logcat :

2020-01-26 15:09:31.480 13943-13943/com.example.odpodstaw D/Data: TestLastname
2020-01-26 15:09:31.480 13943-13943/com.example.odpodstaw D/Data: TestName

I'd like to use it in App How to get it to varable? in MainActivity I've got

lateinit var name :String lateinit var lastname :String

how to get values from database to name and lastname in MainActivity?

I'm just learning and I really don't know how to do this and how to use this data in my app.

  • 1
    It sounds like you're trying to use the values outside of `onDataChange`, which isn't possible. For more on the why of this, and how to still have maintainable code despite this, see https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Jan 26 '20 at 17:01
  • There two answers there, one with a callback and using coroutines. – Alex Mamo Jan 27 '20 at 12:50

1 Answers1

0

Assuming that this fetch is happening inside the MainActivity, you can do the following in the callback where you receive the data:

val activity = this@MainActivity
activity.name = name
activity.lastname = lastname

This sets the properties on the MainActivity.

Bradley Mackey
  • 6,777
  • 5
  • 31
  • 45
  • I don't understand yet. I need to get: "TestLastname" value as ```lastname``` in MainActivity and "TestName" value as ```name``` in MainActivity – AzCodeDevelopment Jan 26 '20 at 15:42