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