我在sqlite db上使用了游标来获取记录。
我的代码如下:
btnnext.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
displayQuestion();
});
}
private void displayQuestion() {
db.openDataBase();
SQLiteDatabase sqlitedatabase = db.getWritableDatabase();
Cursor cur;
cur = sqlitedatabase.rawQuery("select quiz_id, opt_ans from options" ,null);
cur.moveToFirst();
db.close();
radioGroup.removeAllViews();
for (int i = 0; i <= 3; i++) {
l++;
Log.v("value of l",l+"");
radioButton = new RadioButton(this);
String str_opt = cur.getString(cur.getColumnIndex(Database_helper_class.OPT_ID));
radioButton.setText(str_opt);
Log.v("value of l",l+""+str_opt);
radioButton.setId(i);
cur.moveToPosition(l);
radioGroup.addView(radioButton);
}
}
我得到的日志是:
03-07 18:32:03.190: V/value of l(28903): 1video
03-07 18:32:03.200: V/value of l(28903): 2
03-07 18:32:03.210: V/value of l(28903): 2sound
03-07 18:32:03.210: V/value of l(28903): 3
03-07 18:32:03.221: V/value of l(28903): 3image
03-07 18:32:03.231: V/value of l(28903): 4
03-07 18:32:03.240: V/value of l(28903): 4word document
03-07 18:32:05.561: V/value of l(28903): 5
03-07 18:32:05.571: V/value of l(28903): 5video
03-07 18:32:05.580: V/value of l(28903): 6
03-07 18:32:05.590: V/value of l(28903): 6A process
03-07 18:32:05.590: V/value of l(28903): 7
03-07 18:32:05.601: V/value of l(28903): 7A system software
03-07 18:32:05.601: V/value of l(28903): 8
03-07 18:32:05.610: V/value of l(28903): 8A document
我正在使用的数据库是
opt_ans,"opt_id","quiz_id"
video,"1","1"
sound,"2","2"
image,"3","3"
word document,"4","4"
appliction,"5","5"
A process,"6","6"
A system software,"7","7"
A document,"8","8"
hgfhgfh,"9","9"
hgfhgf,"10","10"
tytrytr,"11","11"
ytrytrytr,"12","12"
tytrytrytr,"13","13"
tytrytryt,"14","14"
tytyt,"15","15"
ytytyt,"16","16"
ytytryt,"17","17"
tytytr,"18","18"
tytytryt,"19","19"
htghyt,"20","20"
现在我的问题:
为什么我在第5和第9个索引上获得视频,同时在这些索引上有不同的值?
答案 0 :(得分:1)
除非您指定,否则SQL不保证返回行的任何顺序。基本上,您的结果可能是随机顺序。因此,您需要按如下方式更改查询:
cur = sqlitedatabase.rawQuery("select quiz_id, opt_ans from options order by quiz_id asc" ,null);
修改强>
另外我猜你没有正确地迭代光标,试试这个:
int i = 0;
for (boolean hasItem = cur.moveToFirst(); hasItem; hasItem = cur.moveToNext()) {
if (i < 4) {
radioButton = new RadioButton(this);
String str_opt = cur.getString(cur.getColumnIndex(Database_helper_class.OPT_ID));
radioButton.setText(str_opt);
radioButton.setId(i);
radioGroup.addView(radioButton);
Log.v("Value of button " + i + " is: " + str_opt);
i++;
}
else {
break;
}
}