【问题标题】:The Value of ArrayList is different Outside the Anonymous Inner Class [duplicate]ArrayList 的值在匿名内部类之外是不同的[重复]
【发布时间】:2019-03-11 15:57:06
【问题描述】:

我正在尝试从 FireBase 数据库填充一个 ArrayList。 ArrayList 在 Event Listener 内的大小实际上等于某个数字,但在 Listener 外的值为零。

问题数组的大小值应该大于零,因为我在其中添加元素。 请帮助我找出问题所在。因为我一直在尝试几个小时来解决这个问题。

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()));


}
}

【问题讨论】:

标签: java android firebase arraylist firebase-realtime-database


【解决方案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));
    }

然后告诉我们。

【讨论】:

  • 是的!它从 Firebase 获取数据。数据可用于 OnDataChange() 但函数外没有数据
猜你喜欢
  • 2014-07-17
  • 2010-09-08
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-03
相关资源
最近更新 更多