我正在尝试查询sqlite数据库并将所选数据存储到2d数组中。
我的问题是插入" WHERE字段='波尔多'"进入查询导致错误," android.database.CursorIndexOutOfBoundsExeption:请求索引1,大小为1。" 没有它,查询和数组似乎运行良好。
另外,我发现查询用" WHERE ..."当我删除" c.moveToNext();"时,只能显示一条适当的记录。从数组部分。
可以肯定的是,我的sqlite数据库包含足够的数据来匹配我的查询。
对不起我的解释不好,但我不明白原因。 你能告诉我为什么吗?
我的代码如下。
public String [] [] onQuestion(){
mDbHelper = new MySQLHelper(this);
db = mDbHelper.getWritableDatabase();
Cursor c = db.rawQuery("SELECT field, question, choice1, choice2, choice3, choice4, answer FROM WineQuiz WHERE field= 'bordeaux' ORDER BY RANDOM() LIMIT 5", null);
if(c.moveToFirst());{
for (int ii = 0; ii < array.length; ii++) {
array[ii][0] = c.getString(c.getColumnIndex("field"));
array[ii][1] = c.getString(c.getColumnIndex("question"));
array[ii][2] = c.getString(c.getColumnIndex("choice1"));
array[ii][3] = c.getString(c.getColumnIndex("choice2"));
array[ii][4] = c.getString(c.getColumnIndex("choice3"));
array[ii][5] = c.getString(c.getColumnIndex("choice4"));
array[ii][6] = c.getString(c.getColumnIndex("answer"));
c.moveToNext();
}
db.close();
}
}
return array;
}
答案 0 :(得分:1)
是的,看起来你实际上并没有返回五行......如果有的话。在;
条件之后添加if
会使其无效。删除;
以确保没有空光标,并在每次额外迭代之前检查您是否仍有可用记录:
if( c.moveToFirst() ) {
for (int ii = 0; ii < array.length && !c.isAfterLast(); ii++) {
array[ii][0] = c.getString(c.getColumnIndex( "field"));
array[ii][1] = c.getString(c.getColumnIndex( "question" ));
array[ii][2] = c.getString(c.getColumnIndex( "choice1" ));
array[ii][3] = c.getString(c.getColumnIndex( "choice2" ));
array[ii][4] = c.getString(c.getColumnIndex( "choice3" ));
array[ii][5] = c.getString(c.getColumnIndex( "choice4" ));
array[ii][6] = c.getString(c.getColumnIndex( "answer" ));
c.moveToNext();
}
}
答案 1 :(得分:1)
你应该试试这个......
mDbHelper = new MySQLHelper(this);
db = mDbHelper.getWritableDatabase();
int cPos; // for cursor position
Cursor c = db.rawQuery("SELECT field, question, choice1, choice2, "
+ "choice3, choice4, answer FROM WineQuiz "
+ "WHERE field= 'bordeaux' ORDER BY RANDOM() LIMIT 5", null);
if (c.getCount() > 0) { // If cursor has atleast one row
String[][] array = new String[c.getCount()][7]; // Dynamic string array
c.moveToFirst();
do { // always prefer do while loop while you deal with database
cPos = c.getPosition();
array[cPos][0] = c.getString(c.getColumnIndex("field"));
array[cPos][1] = c.getString(c.getColumnIndex("question"));
array[cPos][2] = c.getString(c.getColumnIndex("choice1"));
array[cPos][3] = c.getString(c.getColumnIndex("choice2"));
array[cPos][4] = c.getString(c.getColumnIndex("choice3"));
array[cPos][5] = c.getString(c.getColumnIndex("choice4"));
array[cPos][6] = c.getString(c.getColumnIndex("answer"));
c.moveToNext();
} while (!c.isAfterLast());
} else {
Log.e("SQL Query Error", "Cursor has no data");
}