FS DB Add Listener

Advertisements
//Getting reference
final DocumentReference docRef = db.collection("users").document("new doc");


docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
    @Override
    public void onEvent(@Nullable DocumentSnapshot snapshot,
                        @Nullable FirebaseFirestoreException e) {
        //This method will be called for the first time when executed and 
        //everytime data is updated in Firebase Firestore by anyone
        
        //Check if there is any expection
        if (e != null) {
            //Somthing went wrong, printing the error message to log
            Log.w(TAG, "Listen failed.", e);
            return;
        }
        //There is no error
        
        //Checking is snapshop is not null and exists
        if (snapshot != null && snapshot.exists()) {
            //Logging data to log
            Log.d(TAG, "Current data: " + snapshot.getData());
            
        } else {
            Log.d(TAG, "Current data: null");
        }
    }
});