如何更改为我可以删除的 ValueEventListener?

How to change to a ValueEventListener that i can remove?

我有一个 Firebase valueEvent 侦听器:

 questions.orderByChild("CategoryID").equalTo(categoryID)
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                        Question ques = postSnapshot.getValue(Question.class);
                        Common.questionList.add(ques);
                    }
                    //Random List
                    Collections.shuffle(Common.questionList);
                }

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

                }
            });

作为拥有可以附加和移除的对象的最佳实践,我想将代码更改为 ValueEventListener 对象。我做了以下事情:

mQuestionsListener = questions.orderByChild("CategoryID").equalTo(categoryID)
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                        Question ques = postSnapshot.getValue(Question.class);
                        Common.questionList.add(ques);
                    }
                    //Random List
                    Collections.shuffle(Common.questionList);
                }

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

                }
            });
    questions.addValueEventListener(mQuestionsListener);

但是没有用。 我哪里错了?

您已经在此处添加了一个侦听器 questions.addValueEventListener(mQuestionsListener);,那么您需要声明一个新的 ValueEventListener():

ValueEventListener mQuestionsListener = new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                        Question ques = postSnapshot.getValue(Question.class);
                        Common.questionList.add(ques);
                    }
                    //Random List
                    Collections.shuffle(Common.questionList);
                }

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

                }
            });