Saransh Agarwal
Saransh Agarwal

Reputation: 305

count the number of variables equal to a value in firebase

Hey I am trying to count the number of times a user has answered the question correctly. This is how my database is stored

userid->questionsid1->correectlyanswer "1"

userid->questionsid2->correectlyanswer "0"

userid->questionsid3->correectlyanswer "0"

userid->questionsid4->correectlyanswer "1"

1 signifying that the answer is correct and 0 being incorrect.

here is the code. The value of questioncode is is correct but the value of in checkCorrectAnswer string is always null.

databaseReference1.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int questionsolved = 0;
            for (DataSnapshot userAnswerSnapshot : dataSnapshot.getChildren()) {

                String questionCodeKey = userAnswerSnapshot.getKey();
                String checkCorrectAnswer = userAnswerSnapshot.child(questionCodeKey).child("checkAnswerCorrect").getValue(String.class);    
                if (checkCorrectAnswer.equals("1")) {
                    questionsolved = questionsolved + 1;
                }

            }
            questionSolvedTextview.setText(questionsolved + "");
        };

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
});

Upvotes: 1

Views: 529

Answers (1)

Kurt Acosta
Kurt Acosta

Reputation: 2537

I think you got this line wrong.

String checkCorrectAnswer = userAnswerSnapshot.child(questionCodeKey).child("checkAnswerCorrect").getValue(String.class);

I think you don't need to get the questionCodeKey for this because you are already iterating through the children of your DatabaseReference which I believe is the path to a specific user. If that is the case, you are iterating through the questions already which means you don't have to get the questions because you are already in them. With that, try this and let me know if it works:

String checkCorrectAnswer = userAnswerSnapshot.child("checkAnswerCorrect").getValue(String.class);

Upvotes: 1

Related Questions