I am trying to fetch data from a document on a firebase’s collection that deos contains users(see image 1)enter image description here.
As you can see, there is a collection named Users and two users, and onw I click on one you get to see the fields and their values. Now, what I need is to retrieve the data within the documents (the fields values) and use it for my app, this is comenthing that ius easily accomplished in Java by using a class variable memmber. However, with Kotlin I can’t do that… so I can’t get the data I want out of the scope of the method addOnColeteListener (I use it like this db.collection().document().get().addOnCompleteListener{ // do stuff to retrieve data }, see code bellow). I realized that I gave more code that needed, but i wanted to add more context just jump right to the setUserIfno()
class MainActivity : ComponentActivity() {
@RequiresApi(Build.VERSION_CODES.Q)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
val notificationsDatabase: DatabaseReference = FirebaseDatabase.getInstance().getReference()
val numberOfNotifications: Int = setNotifications(notificationsDatabase)
var currentUser: UserInfo
val mapOfUser: MutableMap<String, String?> = emptyMap<String,String?>().toMutableMap()
var dataSets = listOf<String>()
setUserInfo { user ->
currentUser = UserInfo().copy(
firstname = user.firstname,
lastname = user.lastname,
email = user.email,
phoneNumber = user.phoneNumber,
gender = user.gender,
moreInfo = user.moreInfo,
uri = user.uri
)
logMessage("outsideCurrentUserIs", currentUser.toString())
}
// logMessage("outsideCurrentUserIs", currentUser.toString())
MainBody(
UserInfo(
firstname="Emmanuel",
lastname="Agyapong",
email="[email protected]",
phoneNumber="9293038986",
gender="Male",
moreInfo="An incoming software engineer",
uri="https://firebasestorage.googleapis.com/v0/b/bookme-dc582.appspot.com/o/meAtBCC.jpg?alt=media&token=3d9b481c-9880-445f-939f-3b7bb60f3cbd"
),
numberOfNotifications
)
}
}
}
}
}
private fun setUserInfo (callBack: (UserInfo) -> Unit) {
val firebaseFirestoreInstance = FirebaseAuth.getInstance()
val database: FirebaseFirestore = FirebaseFirestore.getInstance()
database.collection("Users")
.document(firebaseFirestoreInstance.uid.toString())
.get()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val u: UserInfo = UserInfo().copy(
firstname = task.result.data!!["firstname"].toString(),
lastname = task.result.data!!["lastname"].toString(),
email = task.result.data!!["email"].toString(),
phoneNumber = task.result.data!!["phone"].toString(),
gender = task.result.data!!["gender"].toString(),
moreInfo = task.result.data!!["moreInfo"].toString(),
uri = task.result.data!!["profileImage"].toString()
)
callBack(u)
} else {
Log.d(TAG, "Cached get failed: ", task.exception)
}
}
}
In java I could just do this:
private void getUserImageProfileUri() {
firebasefirestore.collection("Users")
.document(currentUserId)
.get()
.addOnSuccessListener(documentSnapshot -> {
userProfileImageURI = (String) documentSnapshot.get("userProfileImageURI");
username = (String) documentSnapshot.get("username");
});
}
I am an Android enthusiast so please understand that I am learning… thanks in advance!
I tried to rertieve data from a document on firebase, but I noticed that I could store the info in a variable only within the scope of .addOnCompleteListener{}, but after that the variable is empty as if I just initialized it. However, when I print the results inside of the adOnCompleteListener{}, I am able to see the values. How did I try to soleve the problem? Implemented different data structures and implemented callback, but nothing worked.
Emmanuel Agyapong is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.