I have a table name Answers in my database with 5 columns _id, b1, b2, b3, b4 and all I’m trying to do is to get the columns b1, b2, b3, b4 randomly in a cursor, I’m able to get them in my cursor in order using the next code:
public Cursor getAllAnswers(int n)
{
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
Cursor curs;
curs=myData.rawQuery("SELECT b1, b2, b3, b4 FROM Answers WHERE _id='"+n+"';", null);
curs.moveToFirst();
myData.close();
return curs;
};
and have tried to get them randomly using
curs=myData.rawQuery("SELECT b1, b2, b3, b4 FROM Answers WHERE _id='"+n+"' ORDER BY RANDOM() LIMIT 1;", null);
but is not working. Thanks for the help in advance
EDITED to show the right way of accomplishing random columns (if you need it too) shown by Geobits:
public Cursor getAllAnswers(int n)
{
String myPath = DB_PATH + DB_NAME;
myData = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String query = "SELECT ";
boolean[] chosen = new boolean[]{false, false, false, false};
Random rand = new Random();
for(int i=0;i<4;i++)
{
if(i > 0)
query += ", ";
int c = rand.nextInt(4);
while(chosen[c])
c = rand.nextInt(4);
chosen[c] = true;
query += "b" + Integer.toString(c+1);
}
query += " FROM Answers WHERE _id='"+n+"';";
Cursor curs;
curs=myData.rawQuery(query, null);
curs.moveToFirst();
myData.close();
return curs;
};
To make sure I understand, you want to get all four columns in a single row, but randomize the columns within the cursor, so your cursor might end up
{b2, b4, b3, b1}, right? Something to mix up multiple choice answers I guess?ORDER BYwon’t help you there, since it orders rows, not columns.SQLite is going to present them in the order you query them, which is
b1, b2, b3, b4currently. To mix them up, you’ll have to randomize the query string itself.Alternatively, you could just get them in order and randomly grab each column using something similar.