Skip to content
Advertisement

What is the proper way to set a value listener in Firebase Cloud database?

I wrote the following code:

connectedGroup.collection("users").document(connectedEmail).get()
              .addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {

            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                Log.d(this.getClass().getName(), "addOnSuccessListener:success");
                if (documentSnapshot.exists()) {
                    connectedFullName = documentSnapshot.getString("fullName");
                    connectedImageURL = documentSnapshot.getString("image");
                }
                setMenuAvatarImage();
                setMenuHeaderMessage();
            }
  }).addOnFailureListener(new OnFailureListener() {

    @Override
    public void onFailure(@NonNull Exception e) {
        Log.d(this.getClass().getName(), "addOnSuccessListener:failed");

        // Set default values in the menu header
        tryRedirectActivity(getIntent());
        setMenuAvatarImage();
        setMenuHeaderMessage();
    }
});

It fetches the user’s full name and image and set them in the menu. I want to set a listener to those two fields so every time there is a change in the database, it will update connectedFullName and connectedImageURL and call the setMenuAvatarImage, setMenuHeaderMessage methods. How can I do it?

Advertisement

Answer

What you’re describing happens when you use Firestore’s

connectedGroup.collection("users").document(connectedEmail)
  .addSnapshotListener(new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot snapshot,
                        @Nullable FirebaseFirestoreException e) {
        if (e != null) {
            Log.w(TAG, "Listen failed.", e);
            return;
        }

        if (snapshot != null && snapshot.exists()) {
            Log.d(TAG, "Current data: " + snapshot.getData());
            ... TODO: do other things with the data here...
        } else {
            Log.d(TAG, "Current data: null");
        }
    }
});

Immediately after attaching the listener, your onEvent will get called with the current snapshot. And then whenever the document changes, it will get called again with the updated snaspshot.

I recommend studying the documentation in listening for realtime updates, as it covers this and much more.

Advertisement