In the onCreate
method of the MainActivity
, I fetch data from the firebase (Colud):
fireDB.collection("users").document(connectedEmail).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if (documentSnapshot.exists()) {
List<DocumentReference> groups = (List<DocumentReference>) documentSnapshot.get("groups");
if (groups != null && groups.size() > 0) {
connectedGroup = groups.get(0);
}
}
// more code
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.d(this.getClass().getName(), "addOnSuccessListener:failed");
}
});
I fetch the group of the user and keep it in the connectedGroup
field of MainActivity
. The activity has a getter method:
public DocumentReference getConnectedGroupReference() {
return this.connectedGroup;
}
In a fragment that I navigate to, from MainActivity
, I call getConnectedGroupReference
in order to get that field. But if I nevigate to the fragment fast enough, this field could be not set yet (because the call to the database is asynchronous. What's the best way to wait until the field is initialized? What should I do if addOnFailureListener
was called and connectedGroup
was not initialized? How to solve a race between the user navigating to the fragment and the database fetching that field?
The easiest solution is to fetch the group name again in the fragment, but is there a better way?
EDIT: I continued investigating and it looks like it's not smart to freeze the screen. Is there a better way?