我正在我的android工作室开发一个简单的测验。我使用的是数据库,但每次用户点击测验按钮时,我都希望将这些问题随机化。到目前为止,我已经创建了5个示例问题。
答案 0 :(得分:1)
我建议做:
适应(如果还没有)您的课程问题,因此您可以在集合中使用,因此不允许重复...(通过此覆盖等于AND哈希码)
填充Collection,随机播放,获取随机元素
这是完全相同的,
你在那里:)
答案 1 :(得分:1)
在Collections.shuffle
上使用List<Question>
,然后在点击按钮时使用Iterator<Question>
选择问题。
假设您为equals
课程同时实施了hashcode
和Question
,那么LinkedHashSet
将删除重复项,因此重复不会发生。
这是一个基于您的类的Activity,它应该显示这些概念。
public class QuizActivityMarketing extends Activity {
private Iterator<Question> questionIterator;
private TextView txtQuestion;
private RadioButton rda, rdb, rdc, rdd;
private Button butNext;
private Question currentQ;
private int score = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Define your views
txtQuestion = (TextView) findViewById(R.id.textView1);
rda = (RadioButton) findViewById(R.id.radio0);
rdb = (RadioButton) findViewById(R.id.radio1);
rdc = (RadioButton) findViewById(R.id.radio2);
rdd = (RadioButton) findViewById(R.id.radio3);
butNext = (Button) findViewById(R.id.button1);
// Get and randomize the questions
DbHelperMarketing db = new DbHelperMarketing(this);
final List<Question> questions = db.getAllQuestions();
Collections.shuffle(questions);
questionIterator = new LinkedHashSet<Question>(questions).iterator();
// Setup the first question
if (questionIterator.hasNext()) {
currentQ = questionIterator.next();
setQuestionView(currentQ);
}
// Hook up the button-clicking
butNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Check the correct answer
RadioGroup grp = (RadioGroup) findViewById(R.id.radioGroup1);
RadioButton answer = (RadioButton) findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER() + " " + answer.getText());
if (currentQ.getANSWER().equals(answer.getText())) {
score++;
Log.d("score", "Your score" + score);
}
// Load the next question, if there are any
if (questionIterator.hasNext()) {
currentQ = questionIterator.next();
setQuestionView(currentQ);
} else { // Done asking questions
setQuestionView(null);
Intent intent = new Intent(QuizActivityMarketing.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
private void setQuestionView(Question currentQuestion) {
if (currentQuestion != null) {
txtQuestion.setText(currentQuestion.getQUESTION());
rda.setText(currentQuestion.getOPTA());
rdb.setText(currentQuestion.getOPTB());
rdc.setText(currentQuestion.getOPTC());
rdd.setText(currentQuestion.getOPTD());
} else {
txtQuestion.setText("");
rda.setText("");
rdb.setText("");
rdc.setText("");
rdd.setText("");
}
}
}