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

问题描述 投票:0回答:1

我有一个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);

但不起作用。我在哪里错了?

android firebase firebase-realtime-database event-listener
1个回答
1
投票

您已经在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) {

                }
            });
© www.soinside.com 2019 - 2024. All rights reserved.