我正在尝试从FireBase数据库填充ArrayList。在事件侦听器中,ArrayList的大小实际上等于某个数字,但在侦听器之外,值为零。
问题数组的大小值应大于零,因为我正在其中添加元素。 请帮助我找出问题所在。我一直在努力解决这个问题。
ArrayList <Question> questions = new ArrayList<Question>();
int totalQuestCount =0;
FirebaseDatabase fDataBase;
DatabaseReference quizRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_interface);
Log.d("QUESTION_SIZE1", String.valueOf(questions.size()));
fDataBase = FirebaseDatabase.getInstance();
quizRef = fDataBase.getReference("quizes/quiz1");
quizRef.keepSynced(true);
quizRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.hasChildren()){
totalQuestCount=(int)dataSnapshot.getChildrenCount();
questions.ensureCapacity(totalQuestCount);
Log.d("QuestionCount", String.valueOf(totalQuestCount));
for(DataSnapshot data: dataSnapshot.getChildren()){
questions.add(data.getValue(Question.class));
}
Log.d("QUESTION_SIZE2", String.valueOf(questions.size()));
}else{
Log.d("DATASNAP", "DOES NOT EXISTS");
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
Log.d("QUESTION_SIZE3", String.valueOf(questions.size()));
}
}
答案 0 :(得分:1)
在此区块
for(DataSnapshot data: dataSnapshot.getChildren()){
questions.add(data.getValue(Question.class));
}
放入
System.out.println(data.getValue(Question.class));
并检查您是否实际上是从firebase获取数据并将其添加。?
喜欢
for(DataSnapshot data: dataSnapshot.getChildren()){
System.out.println(data.getValue(Question.class));
questions.add(data.getValue(Question.class));
}
然后让我们知道。