Reputation: 432
I have a valueEventListener() that is used to get the data from Firebase.
Here is the first one.
sectionReference.child(classID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
uidArrayList.add(snapshot.getKey());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {}
});
}
I want to get the list of UIDs in the uidArrayList and use it to do some other functionality.
Here is the second one.
mRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
getUIDsInCurrentClass();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
if(user.getRole().equals("student") && uidArrayList.contains(user.getUid())){
studentArrayList.add(user);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {}
});
}
In this second Listener, you can see that I want to access the contents of uidArrayList. I saw using Log.d that the size of the ArrayList was 0, which meant that it was not initialised when it was called in the second listener.
Is there any way that I can make sure that the uidArrayList is initialised with all the values before it is accessed in the next ValueEventListener().
I have tried doing this, Event Handlers & Event Listeners Independent of one Another
But it did not work for me. Thanks in advance for the answer.
Upvotes: 1
Views: 701
Reputation: 138824
Is there any way that I can make sure that the
uidArrayList
is initialized with all the values before it is accessed in the next ValueEventListener()?
Yes it is. The simplest solution I can think of is to use nested queries. So the second query must nested in the first one so you can be sure that your uidArrayList
is not empty. So the code should look something line this:
sectionReference.child(classID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
uidArrayList.add(snapshot.getKey());
}
mRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//getUIDsInCurrentClass();
for(DataSnapshot snapshot: dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
if(user.getRole().equals("student") && uidArrayList.contains(user.getUid())){
studentArrayList.add(user);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError dbError) {
Log.d("TAG", dbError.getMessage()); //Don't ignore potential errors!
}
});
Upvotes: 2