Reputation: 1412
I want to extract random rows from the app sqlite database in Android. I'm aware that, with sqlite, you can select random rows with:
SELECT * FROM table ORDER BY RANDOM() LIMIT 1;
In the app, I have something like this
return mDb.query(TABLE, new String[] {"col1", "col2"}, null, null, null, null, "Random()", "2");
this is for extract two random rows in table TABLE. But it keeps returning the same rows. What's wrong wit the statement?
Thanks
Upvotes: 10
Views: 9727
Reputation: 52800
Set query like below:
public Cursor getRandomDataItemFromDb(String tableName, int limit) {
Cursor cursor = db.rawQuery("SELECT * FROM " + tableName+ " ORDER BY RANDOM() LIMIT " + limit, null);
if (cursor.moveToFirst()) {
return cursor;
}
return cursor;
}
Done
Upvotes: 4
Reputation: 3725
Use the random function as in a string in your query. I gave you a sample below.
String orderBy = "RANDOM()";
Cursor dbc = this.db.query(TABLE_NAME, columnArray, null, null, null, null, orderBy, null);
Upvotes: 2
Reputation: 12739
Use the orderBy clause like this
Cursor cursor = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, "RANDOM() limit 1");
Upvotes: 3
Reputation: 3084
try this
Cursor cursor = this.db.query("YourTable Order BY RANDOM() LIMIT 1",
new String[] { "*" }, null, null, null, null, null);
Upvotes: 22