我正在尝试进行多重答案测验。我关注了这个网站: Simple Quiz Game
在Multiple Activity中,我添加了这个:
QuestionsDbHelper db = new QuestionsDbHelper(this);
questionsList = db.getAllQuestions();
currentQuestion=questionsList.get(questionId);
正如你在最后一行所看到的,我得到了这个错误。在QuestionsDbHelper中,我添加了问题,但仍然无法在Activity上显示它们。 我已经描述了Manifest文件中的Activity。 我从Debug中可以理解的是我的Array是空的,但是我已经插入了问题列表。
有什么想法吗?
Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at com.game.mlm.q2game.MultipleMode.onCreate(MultipleMode.java:36)
我发布的代码没有onCreate和onUpgrade,因为它们非常基本。 这是我的QuestionsDbhelper代码:
public void addQuestions(Questions question){
Log.d("add Questions" , question.toString());
// SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_QUESTION, question.getQuestion());
values.put(KEY_ANSWER, question.getAnswer());
values.put(KEY_FBUTTON, question.getFirstButton());
values.put(KEY_SBUTTON, question.getSecondButton());
values.put(KEY_THBUTTON, question.getThirdButton());
dbase.insert(TABLE_QUESTIONS, null, values);
}
public List<Questions> getAllQuestions(){
List<Questions> questionsList = new ArrayList<Questions>();
//SELECT ALL FROM QUERY
String selectQuery = "SELECT * FROM " + TABLE_QUESTIONS;
dbase= this.getReadableDatabase();
Cursor cursor = dbase.rawQuery(selectQuery, null);
//LOOPING THROUGH ALL ROWS AND ADDING TO LIST
if (cursor.moveToFirst()) {
do {
Questions question = new Questions();
question.setId(cursor.getInt(0));
question.setQuestion(cursor.getString(1));
question.setAnswer(cursor.getString(2));
question.setFirstButton(cursor.getString(3));
question.setSecondButton(cursor.getString(4));
question.setThirdButton(cursor.getString(5));
questionsList.add(question);
}
while (cursor.moveToNext());
}
Log.d( "getAllQuestions()", questionsList.toString() );
return questionsList;
}
public int rowcount() {
int row = 0;
String selectQuery = "SELECT * FROM " + TABLE_QUESTIONS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
row = cursor.getCount();
// cursor.close();
return row;
}
答案 0 :(得分:0)
您是否检查过问题是否正确?您可能没有使用的问题ID的数据
答案 1 :(得分:0)
首先检查数据库中的rowCount返回值。 如果是,则使用
将光标移动到第一个位置 cursor.moveToFirst();
答案 2 :(得分:0)
使用getAllQuestions()
中的QuestionsDbHelper class
方法中的这一行。
String Query = "select * from <table name>";
db = openDataBase();
Cursor cursor = db.rawQuery(Query, null);
// Log.d(LOG_TAG, "Cursor Length: " + cursor.getCount());
while (cursor.moveToNext()) {
<Get all data from table>
}