【问题标题】:How to get random qestion from firebase firestore database如何从 firebase firestore 数据库中获取随机 qestion
【发布时间】:2021-04-06 08:32:14
【问题描述】:

我正在制作一个测验应用程序,其中我有类别,当我选择一个类别时,qestions 开始来自 firebase firestore 数据库,在每个类别中我在数据库中有 10 个 qestion,我希望所有 qestions 从 firebase 数据库加载并且每次都是随机出现的,

但我的问题是所有问题都没有加载,有时加载 5,有时加载 7,并且这个随机顺序继续..

我对 firebase 数据库了解不多,下面是我尝试过的代码

我的 QuizzActivity 代码

public class QuizActivity extends AppCompatActivity {

ActivityQuizBinding binding;

ArrayList<Questions> qestions;

Questions question;

CountDownTimer timer;

FirebaseFirestore database;

int correctAnswer = 0;

int index = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);



    binding = ActivityQuizBinding.inflate(getLayoutInflater());
    setContentView(binding.getRoot());

    qestions = new ArrayList<>();
    database = FirebaseFirestore.getInstance();

  final   String cateGoryID = getIntent().getStringExtra("categoryID");

    Random random = new Random();
  final   int rand = random.nextInt(10);

    database.collection("categories")
            .document(cateGoryID)
            .collection("questions")
            .whereGreaterThanOrEqualTo("index",rand)
            .orderBy("index")
            .limit(5)
            .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            if (queryDocumentSnapshots.getDocuments().size()<5){

                database.collection("categories")
                        .document(cateGoryID)
                        .collection("questions")
                        .whereLessThanOrEqualTo("index",rand)
                        .orderBy("index")
                        .limit(5)
                        .get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        for (DocumentSnapshot snapshot : queryDocumentSnapshots){
                                Questions questions = snapshot.toObject(Questions.class);
                                qestions.add(questions);
                            }
                        setNextQestions();

                    }
                });


            } else {

                for (DocumentSnapshot snapshot : queryDocumentSnapshots){
                    Questions questions = snapshot.toObject(Questions.class);
                    qestions.add(questions);
                }
                setNextQestions();


            }
        }
    });


     resetTimer();

}

void resetTimer(){

    timer = new CountDownTimer(30000,1000) {
        @Override
        public void onTick(long l) {

            binding.timer.setText(String.valueOf(l/1000));

        }

        @Override
        public void onFinish() {

        }
    };
}

public void CheckAnwer(TextView textView){
    String selectAnswer = textView.getText().toString();
    if(selectAnswer.equals(question.getAnswer())){
        correctAnswer++ ;
        textView.setBackground(getResources().getDrawable(R.drawable.option_right));
    }
    else{
        showAnswer();
        textView.setBackground(getResources().getDrawable(R.drawable.option_wrong));
    }
}


@Override
public void onBackPressed() {
    new AlertDialog.Builder(QuizActivity.this)
            .setIcon(R.drawable.ic_baseline_person_24)
            .setMessage("Are you sure want to Quit Game")
            .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent in = new Intent(QuizActivity.this,MainActivity.class);
                    startActivity(in);
                    finish();
                }
            }).setNegativeButton("No", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            dialogInterface.dismiss();
        }
    }).create().show();

}


public void setNextQestions() {

    if(timer != null){
        timer.cancel();
    }




    timer.start();



    if (index < qestions.size()) {

        binding.qestioncounter.setText(String.format("%d/%d",(index+1),qestions.size()));
         question = qestions.get(index);
        binding.qestions.setText(question.getQestion());
        binding.option1.setText(question.getOption1());
        binding.option2.setText(question.getOption2());
        binding.option3.setText(question.getOption3());
        binding.option4.setText(question.getOption4());

    }
}

void reset(){
    binding.option1.setBackground(getResources().getDrawable(R.drawable.option_unselected));
    binding.option2.setBackground(getResources().getDrawable(R.drawable.option_unselected));
    binding.option3.setBackground(getResources().getDrawable(R.drawable.option_unselected));
    binding.option4.setBackground(getResources().getDrawable(R.drawable.option_unselected));
}


void showAnswer(){
    if (question.getAnswer().equals(binding.option1.getText().toString()))
        binding.option1.setBackground(getResources().getDrawable(R.drawable.option_right));

    else  if (question.getAnswer().equals(binding.option2.getText().toString()))
        binding.option2.setBackground(getResources().getDrawable(R.drawable.option_right));

    else  if (question.getAnswer().equals(binding.option3.getText().toString()))
        binding.option3.setBackground(getResources().getDrawable(R.drawable.option_right));

    else  if (question.getAnswer().equals(binding.option4.getText().toString()))
        binding.option4.setBackground(getResources().getDrawable(R.drawable.option_right));

}

public void onClick(View view){
    switch (view.getId()){

        case R.id.option_1:

        case R.id.option_2:
        case R.id.option_3:
        case R.id.option_4:
            if(timer != null){
                timer.cancel();
            }
            TextView selected = (TextView) view;
            CheckAnwer(selected);
            break;

        case R.id.next_btn:
            // reset();
            if (index < qestions.size()){
                reset();
            index++;
            setNextQestions();}
            else {

                Toast.makeText(this, "Quiz Finsished", Toast.LENGTH_SHORT).show();
                Intent in = new Intent(QuizActivity.this,ResultActivity.class);
                in.putExtra("correct_answer",correctAnswer);
                in.putExtra("total",qestions.size());
                startActivity(in);

            }
            break;







    }
}

【问题讨论】:

    标签: java android firebase


    【解决方案1】:

    最简单的做法是在不使用随机的情况下加载所有问题,并将所有问题添加到 qestions 数组列表中,然后随机播放。

    for (DocumentSnapshot snapshot : queryDocumentSnapshots){
        Questions questions = snapshot.toObject(Questions.class);
        qestions.add(questions);
    }
    Collections.shuffle(questions);
    setNextQestions();
    

    进行这样的更改。

    case R.id.next_btn:
        setNextQestions();
        break;
    

    setNextQestions方法

    public void setNextQestions() {
        if(timer != null){
            timer.cancel();
        }
    
        timer.start();
    
    if (index < qestions.size()) {
        binding.qestioncounter.setText(String.format("%d/%d",(index+1),qestions.size()));
        question = qestions.get(index);
        binding.qestions.setText(question.getQestion());
        binding.option1.setText(question.getOption1());
        binding.option2.setText(question.getOption2());
        binding.option3.setText(question.getOption3());
        binding.option4.setText(question.getOption4());
        index++;
    }
    else {
        reset();
        Toast.makeText(this, "Quiz Finsished", Toast.LENGTH_SHORT).show();
        Intent in = new Intent(QuizActivity.this,ResultActivity.class);
        in.putExtra("correct_answer",correctAnswer);
        in.putExtra("total",qestions.size());
        startActivity(in);
    }
    }
    

    【讨论】:

    • 你能帮我提供所需的代码吗
    • 一切都很好,但唯一的问题是当它到达最后一个问题时,我按下下一个按钮它再次重置相同的最后一个问题,简单来说我必须在到达后按两次下一个按钮最后的问题然后我的结果活动正在打开
    • if (index
    • 当我这样做时,当我按下下一个按钮时,第一个问题正在重置
    猜你喜欢
    • 2017-07-06
    • 1970-01-01
    • 2017-04-07
    • 2021-11-05
    • 1970-01-01
    • 2019-05-10
    • 1970-01-01
    • 1970-01-01
    • 2022-06-27
    相关资源
    最近更新 更多