在Firebase中进行循环查询

时间:2018-12-19 10:46:42

标签: java android firebase firebase-realtime-database

我有这段代码,我的目标是将邮件发送给收件人,例如电子邮件(Cc),但它不会循环,我有2个收件人,但我只能向第一个发送邮件。

DatabaseReference emailReference = firebaseDatabase.getReference(STUDENTS);
DatabaseReference carbonCopyReference = firebaseDatabase.getReference(STUDENTS);
emailReference.keepSynced(true);
carbonCopyReference.keepSynced(true);
List<String> carbonUids = new ArrayList<>();
carbonUids.clear();

for (int i = 0, emailsSize = emails.size(); i < emailsSize; i++) {

    String email = emails.get(i);
    Log.d("interactor--emails", email);
    Query emailQuery = emailReference.orderByChild("email").startAt(email).endAt(email+UF8FF);
    emailQuery.keepSynced(true);

    emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                carbonUids.add(snapshot.getKey());
                Log.d("interactor--carbonKey", String.valueOf(carbonUids));
                for (String carbonUid : carbonUids) {

                    carbonCopyReference.child(carbonUid).child(CONSULTATION_REQUESTS).push().setValue(response);
                }
            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            listener.onFailure(databaseError.getMessage());
        }
    });
    if (i == (emails.size()-1)){
        listener.onSuccess("Request Sent");
        context.startActivity(new Intent(context, ConsultDepartmentsActivity.class));
        ((Activity) context).finish();
        ((Activity) context).overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
    }
}

2个记录在第一个收件人中,而没有记录发送到第二个。 (我仍然没有10个信誉点来发布图片)

第一个收件人中有2条记录-

2 records in first recipient

具有公开详细信息(例如电子邮件,fName)的孩子是我的目标收件人

具有公开详细信息(电子邮件,fName,lastName)的孩子-

Child with open details (email, fName, lastName)

我看到了这段代码,但是我不知道如何用Java做到这一点。至少在Java中这可能可行吗?

for (var each = 0; each < alumAroundId.length; each++) { 
console.log("outside of rootRef", each); 
(function(each){ rootRef.child('users').child(alumAroundId[each].key).once('value', function (eventSnap) 
{ 
console.log(each, "inside the rootRef is off"); var thisUser = eventSnap.val(); thisUser.distance = alumAroundId[each].distance; $scope.allAlumAround.push(thisUser); 
}); 
})(each); 
}

2 个答案:

答案 0 :(得分:0)

The problem in your code is that you are iterating the carbonUids list while adding elements to the same list. To solve this, you need to get that for loop out of the other for loop like this:

emailQuery.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
            carbonUids.add(snapshot.getKey());
            Log.d("interactor--carbonKey", String.valueOf(carbonUids));

        }

        for (String carbonUid : carbonUids) {
            carbonCopyReference.child(carbonUid).child(CONSULTATION_REQUESTS).push().setValue(response);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        listener.onFailure(databaseError.getMessage());
    }
});

答案 1 :(得分:0)

我在列表中发现第二个电子邮件项目带有空格。我必须将.trim()添加到email字符串变量中,以便查询代码读取for循环中的每封电子邮件。

Finally it worked after adding trim() to email string

这是工作代码

for (int i = 0; i < emails.size(); i++) {
 String email = emails.get(i);
 Log.d("interactor--email", email.trim());
 Log.d("interactor--last-emails", String.valueOf(emails).trim());

 queryReference(emailReference, carbonCopyReference, email.trim(), response, listener);
}

private void queryReference( DatabaseReference emailReference, DatabaseReference carbonCopyReference, String email, ConsultationResponse response, SendingMessageListener listener) {
    emailReference.orderByChild("email").equalTo(email).addChildEventListener(new ChildEventListener() { //.startAt(classmateEmails[i]).endAt(classmateEmails[i]+UF8FF)
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            Log.d("interactor--snapshotKey", dataSnapshot.getKey());
            List<String> carbonUids = new ArrayList<>();
            carbonUids.add(dataSnapshot.getKey());
            Log.d("interactor--emailSnap", email);

            Log.d("interactor--carbonKey1", String.valueOf(carbonUids));
            Log.d("interactor--carbonSize1", String.valueOf(carbonUids.size()));

            for (int i = 0; i < carbonUids.size(); i++) {
                String carbonUid = carbonUids.get(i);
                Log.d("interactor--carbonLoop", carbonUid);
                carbonCopyReference.child(carbonUid).child(CONSULTATION_REQUESTS).push().setValue(response);
                if (i == (carbonUids.size() - 1)) { //i == (emails.size() - 1)
                    Log.d("interactor--finishLoop", "Loop finished.");
                    listener.onSuccess("Request Sent");
                    context.startActivity(new Intent(context, ConsultDepartmentsActivity.class));
                    ((Activity) context).finish();
                    ((Activity) context).overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
                }
            }
        }

        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

        }

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

        }

        @Override
        public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

Data added to recipients. Yaaay! (I don't have 10 reputation points yet, please bear with me)