首页 > 解决方案 > 使用 while 循环遍历 Firebase 数据库

问题描述

我创建了一个复习问题表,每次用户答错问题时,都会将一个问题添加到此表中。尝试使用此功能时,我会遍历表格以显示每个问题。

像这样:

databaseref = FirebaseDatabase.getInstance().getReference().child("Review Questions").child(userid).child("Pollution");

databaseref.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
       final  Iterator<DataSnapshot> questions = dataSnapshot.getChildren().iterator();
        while (questions.hasNext()) {
            final DataSnapshot question = questions.next();
            t1_question.setText(question.child("question").getValue().toString());
            b1.setText(question.child("answer1").getValue().toString());
            b2.setText(question.child("answer2").getValue().toString());
            b3.setText(question.child("answer3").getValue().toString());
            b4.setText(question.child("answerCorrect").getValue().toString());



            b1.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {

                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            incorrect++;
                            b1.setBackgroundColor(Color.RED);
                            b4.setBackgroundColor(Color.GREEN);

                            description.setBackgroundColor(Color.YELLOW);
                            description.setText(question.child("description").getValue().toString());


                        }

我有四个按钮,我刚刚展示了一个按钮作为示例。出于某种原因,它显示了复习问题表中的最后一个问题。所以它不会遍历它们,因为最后一个问题没有下一个值。

我还有一个下一个按钮,它应该用来进入下一个问题,写成这样:

  next.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    b2.setBackgroundColor(Color.LTGRAY);
                    b1.setBackgroundColor(Color.LTGRAY);
                    b3.setBackgroundColor(Color.LTGRAY);
                    b4.setBackgroundColor(Color.LTGRAY);
                    description.setText("");
                    description.setBackgroundColor(Color.WHITE);
                    total = total + 1;

                    UpdateQuestion();
                }
            }, 1500);
        }
    });

显示的数据库树及其打印的问题已圈出:

数据库树

我的代码有问题吗?

我似乎无法理解它为什么会这样,

是否有可能正在阅读其他问题,尽管我看不到这一点,因为没有什么可以暂停 while 循环?如果是这样,我将如何做到这一点

标签: javaandroidfirebasefirebase-realtime-database

解决方案


您在循环的每次迭代中设置相同按钮的标签:

b1.setText(...)

所以在循环b1结束时,answer1以最后一个问题的值结束。

您需要为每个问题拥有/生成 UI 元素(标签、文本视图、按钮)。执行此操作的典型方法是使用RecyclerView. 我建议阅读有关从 firebase 填充 recyclerview 的内容,因为该主题非常广泛。


推荐阅读