我正在创建一个包含不同主题的Android应用测验。所以我在我的数据库中有Quiz1,Quiz2,Quiz3等主题和不同TABLE的按钮......
这是我的Quiz.java代码
public class Quiz extends Activity implements OnClickListener{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz);
Button quiz1 = (Button) findViewById(R.id.quiz1Btn);
quiz1.setOnClickListener(this);
Button quiz2 = (Button) findViewById(R.id.quiz2Btn);
quiz2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent i;
switch (v.getId()){
case R.id.quiz1Btn :
//Get Question set
List<Question> questions = getQuestionSetFromDb();
//Initialize quiz with retrieved question set ///
CurrentQuiz c = new CurrentQuiz();
c.setQuestions(questions);
c.setNumRounds(getNumQuestions());
((MLearningApp)getApplication()).setCurrentGame(c);
i = new Intent(this, QuestionActivity.class);
startActivity(i);
break;
}
}
// Method that retrieves a random set of questions from db
private List<Question> getQuestionSetFromDb() throws Error {
int numQuestions = getNumQuestions();
DBHelper myDbHelper = new DBHelper(this);
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
List<Question> questions = myDbHelper.getQuestionSet(numQuestions);
myDbHelper.close();
return questions;
}
// Method to return the number of questions for the game
private int getNumQuestions() {
int numRounds = 10;
return numRounds;
}
这是我在DBHelper.java中的查询
public List<Question> getQuestionSet(int numQ){
List<Question> questionSet = new ArrayList<Question>();
Cursor c = myDataBase.rawQuery("SELECT * FROM Quiz1" + " ORDER BY RANDOM() LIMIT " + numQ, null);
while (c.moveToNext()){
//Log.d("QUESTION", "Question Found in DB: " + c.getString(1));
Question q = new Question();
q.setQuestion(c.getString(1));
q.setAnswer(c.getString(2));
q.setOption1(c.getString(3));
q.setOption2(c.getString(4));
questionSet.add(q);
}
return questionSet;
}
我的问题是,如何在我的数据库中为Quiz2按钮选择Quiz2 TABLE;和Quiz3按钮中的Quiz3 TABLE相同,等等。
到目前为止,我的Android应用程序仅适用于Quiz1,因为它只从我的数据库中检索一个用于Quiz1的表。
答案 0 :(得分:2)
您必须将表名更改为Quiz2
等。
这要求函数需要知道测验号:
public List<Question> getQuestionSet(int quizNr, int numQ) {
...
rawQuery("SELECT * FROM Quiz" + quizNr + " ORDER BY random() LIMIT " + numQ, null);
...
}
如果您有一个表,则必须过滤相应的列:
public List<Question> getQuestionSet(int quizNr, int numQ) {
...
rawQuery("SELECT * FROM Quiz WHERE QuizNr = " + quizNr + " ORDER BY random() LIMIT " + numQ, null);
...
}