• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps sqlite query random example

ronnixw

Newbie
Hello,

can you please show me an example how to select random rows from database using :
db.query(table, columns, selection, selectionArgs, groupBy, having, orderBy)

best regards,
Uldis
 
Code:
Random r = new Random();
db.query(true, DB_TABLE, new String[] { "_id" }, "_id = ?", new String[] { String.valueOf(r.nextInt(100)) }, null, null, null, null);
 
Thank you , but if I am true , this is not the way I was asking for.
I wanted sqlite variant not java.

If I understand by using this method , I need to know how much records are into database and they must be without gaps between them?!
And this query will return one row or row group?

best regards,
ronnixw
 
You asked for this method in your question, and this gives you a random row. To get the row count so you dont get IndexOutOfBounds use this:
Code:
Random r = new Random();
db.query(true, DB_TABLE, new String[] { "_id" }, "_id = ?", new String[] { String.valueOf(r.nextInt(getRowCount())) }, null, null, null, null);
Code:
private int getRowCount()
{
    Cursor c = db.query(DB_TABLE, new String[] { "_id" }, null, null, null, null, null);
    int count = c.getCount();
    c.close();
    return count;
}
 
Search google for the 'Random Quotes' example, it uses SQLite and has code examples that do this very task.

From what I currently understand the java code in an android app seems to 'wrap up' the sql commands. I may be wrong, if so please correct me.
 
You asked for this method in your question, and this gives you a random row.

Sorry , I asked for random rowS , it means one query return more than one row in random order ;)

Didn't find better solution than just execute plain sql code :D
 
Back
Top Bottom