Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

android sqlite getting data from database randomly

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...