I have successfully read data from Firebase
and displayed it in an imageView
asynchronously using a completion callback. Being new to programming,
To solve this, you need to create your own callback to wait for Firebase to return you the data. To achieve this, first you need to create an interface
like this:
interface FirebaseCallback {
fun onCallback(list: MutableList<RecipeTemplate>)
}
Then you need to create a function that is actually getting the data from the database. This function should look like this:
fun readFirebaseData(firebaseCallback: FirebaseCallback) {
ref.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val list = ArrayList<RecipeTemplate>()
for (ds in dataSnapshot.getChildren()) {
val recipeTemplate = ds.getValue(RecipeTemplate::class.java!!)
list.add(recipeTemplate)
}
firebaseCallback.onCallback(list)
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
In the end just simply call readData()
function and pass an instance of the FirebaseCallback
interface as an argument wherever you need it like this:
readFirebaseData(object : FirebaseCallback {
override fun onCallback(list: MutableList<RecipeTemplate>) {
//Do what you need to do with your list
}
})
This is the only way in which you can use that value outside onDataChange()
function.