gpt4 book ai didi

java - 如何从sqlite中随机访问问题?

转载 作者:行者123 更新时间:2023-11-30 05:02:07 25 4
gpt4 key购买 nike

我正在构建一个测验应用程序,我想从数据库中的 100 个问题中随机检索 10 个问题。

这是我从数据库中检索问题的代码

QuizDbHelper dbHelper = new QuizDbHelper(this);
questionList = dbHelper.getQuestions(difficulty);
questionCountTotal = questionList.size();
Collections.shuffle(questionList);

QuizDbHelper 类的 getQuestions 方法:

 public ArrayList<Question> getQuestions(String difficulty) {


ArrayList<Question> questionList = new ArrayList<>();
db = getReadableDatabase();
String[] selectionArgs=new String[]{difficulty};
Cursor c = db.rawQuery("SELECT * FROM " + QuestionsTable.TABLE_NAME+ " WHERE " +QuestionsTable.COLUMN_DIFFICULTY+"= ?", selectionArgs);

if (c.moveToFirst()) {
do {
Question question = new Question();
question.setQuestion(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_QUESTION)));
question.setOption1(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION1)));
question.setOption2(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION2)));
question.setOption3(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION3)));
question.setOption4(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_OPTION4)));
question.setAnswerNr(c.getInt(c.getColumnIndex(QuestionsTable.COLUMN_ANSWER_NR)));
question.setDifficulty(c.getString(c.getColumnIndex(QuestionsTable.COLUMN_DIFFICULTY)));
questionList.add(question);
} while (c.moveToNext());
}

c.close();

return questionList;
}

当我运行它时,所有 100 个问题都出现了任何人都可以更好地修复它..

最佳答案

首先从问题数组列表中的数据库中检索所有问题

然后洗牌你的arraylist。

Collections.shuffle(questionList);

并子列表到 10 个赞

   questionList.subList(0,10)

关于java - 如何从sqlite中随机访问问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58081865/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com