【问题标题】:Collections.shuffle(list) doesn't shuffle my listCollections.shuffle(list) 不会打乱我的列表
【发布时间】:2018-05-16 17:23:04
【问题描述】:

我的测验应用程序有问题。我必须重新整理我的问题列表(取自 Firebase 数据库),但我的代码似乎是错误的。

文件 Start.java:

private void loadQuestion(String categoryId) {

        //First, clear list if have old question
        if(Common.questionList.size() > 0)
            Common.questionList.clear();

        questions.orderByChild("CategoryId").equalTo(categoryId)
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
                        {
                            Question ques = postSnapshot.getValue(Question.class);
                            Common.questionList.add(ques);
                        }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });
        //Random list
        Collections.shuffle(Common.questionList);
    }

和文件 Common.java:

public class Common {
    public static String categoryId;
    public  static User currentUser;
    public static List<Question> questionList = new ArrayList<>();
}

谢谢大家。

【问题讨论】:

    标签: java android collections shuffle


    【解决方案1】:

    您的数据正在通过回调addValueEventListener添加

    在函数开始时,清除列表:

            Common.questionList.clear();
    

    所以Collections.suffle 只会在你的空列表上随机播放

    您想要的是将该 shuffle 函数放在您的回调中:

                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
                        {
                            Question ques = postSnapshot.getValue(Question.class);
                            Common.questionList.add(ques);
                        }
                        // Shuffle it
                        Collections.shuffle(Common.questionList);
    
                    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-05
      • 2018-05-24
      • 2012-04-03
      • 2019-10-29
      • 2010-11-01
      • 2021-03-29
      • 1970-01-01
      • 2011-05-03
      相关资源
      最近更新 更多