Home » Android » Random() in sqlite and Android sdk

Random() in sqlite and Android sdk

Posted by: admin May 14, 2020 Leave a comment

Questions:

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

How to&Answers:

try this

Cursor cursor = this.db.query("YourTable Order BY RANDOM() LIMIT 1",
                new String[] { "*" }, null, null, null, null, null);

Answer:

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

Answer:

Use the orderBy clause like this

Cursor cursor = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, "RANDOM() limit 1");

Answer:

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);