Hey I am working on an application where i need to get the keys from the realtime databse's collection i have stored users id's in keys inside the collection. And I am performing a firestore query on the id's I will get from those keys. So when i am trying to get the keys from the realtime databse in a string the string is null here "whereEqualTo("uid", recentUserId)". How can i get the keys so that i can perform the query.
String recentUserId;
// Code to get the user id's from the realtime databse stored in keys
firebaseDatabase.getReference().child("Recent_Chats").child(auth.getUid()).get().addOnSuccessListener(new OnSuccessListener<DataSnapshot>() {
@Override
public void onSuccess(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot1 : dataSnapshot.getChildren()) {
recentUserId = snapshot1.getKey();
Toast.makeText(getContext(), "hey therere" recentUserId, Toast.LENGTH_SHORT).show();
}
}
});
// Code to get the relevent ids user data from firestore
Query query = firebaseFirestore.collection("Users").whereEqualTo("uid", recentUserId);
query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
User obj = d.toObject(User.class);
userArrayList.add(obj);
}
adapter.notifyDataSetChanged();
}
});
I tried some ways, but did not get how to get keys.
CodePudding user response:
Loading data from Firebase (and most modern cloud APIs) is asynchronous, and the way you have written your code now means that the query on Firestore will happen before the recentUserId = snapshot1.getKey();
has ever been set.
To ensure the correct order, all code that needs data from the database has to be inside the onDataChange
that fires when the data is loaded, or be called from there, or be otherwise synchronized.
So the simplest fix is to move the loading from Firestore into the onDataChange
like this:
String recentUserId;
// Code to get the user id's from the realtime databse stored in keys
firebaseDatabase.getReference().child("Recent_Chats").child(auth.getUid()).get().addOnSuccessListener(new OnSuccessListener<DataSnapshot>() {
@Override
public void onSuccess(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot1 : dataSnapshot.getChildren()) {
recentUserId = snapshot1.getKey();
Toast.makeText(getContext(), "hey therere" recentUserId, Toast.LENGTH_SHORT).show();
//