android sqlite getting data from database randomly

2019-09-22 01:09发布

问题:

my database contains questions and each question has three options. everything work fine but when I try to get the questions and options randomly it it gives me errors:

I found similar questions to my problem but it also didn't work,

here is my code:

public List<Test> getTest() {
List<Test> MyList = new ArrayList<Test>();

myDB=this.getReadableDatabase();
Cursor cursor = myDB.rawQuery("SELECT  * FROM " + My_Table + "ORDER BY RANDOM() LIMIT 1", null);

if (cursor.moveToFirst()) {
do {
Test newQ = new Test();
newQ .setId(cursor.getInt(0));
newQ .setTest(cursor.getString(1));
newQ .setAns(cursor.getString(2));
newQ .setO1(cursor.getString(3));
newQ .setO2(cursor.getString(4));
newQ .setO3(cursor.getString(5));
MyList .add(newQ );
} while (cursor.moveToNext());
}
return MyList ;}

when I add this line to my code:

ORDER BY RANDOM() LIMIT 1

the activity will not work.

回答1:

You need to quote the ORDER BY part of the SQL as Java string literal as well:

"SELECT  * FROM " + My_Table + " ORDER BY RANDOM() LIMIT 1"