Select A Random Row In Realm Table
I want to select a random row from the realm table. Something like - SELECT * FROM table ORDER BY RANDOM() LIMIT 1;
Solution 1:
Something like this would do, yes?
Random random = new Random();
RealmResults<YourTable> list = realm.where(YourTable.class).findAll();
YourTable yourTable = list.get(random.nextInt(list.size()));
Solution 2:
Depends on what you want to do:
Do you want to get a random row from a table? Or A (random) row from a random table?
I guess you mean the former: If you have an id in your table, you could just:
SELECT*FROMtable b WHERE id =FLOOR(RAND() * (3-0+1)) +0
You should place a min and max here like so:
FLOOR(RAND() * (<max> - <min> + 1)) + <min>
(as found here)
Solution 3:
SWIFT 5
I do it this way and it works perfect:
letresults = realm.objects(MyObject.self) // Get all the objectsletrandomIndex = Int.random(in: 0 ..< results.count) // Get a random number within the number of objects returnedletrandomObject = results[randomIndex] // Get a random object
Solution 4:
Stringquery=String.format("SELECT * FROM realm ORDER BY %d LIMIT 1", random());
databaseHelper = newDatabaseHelper(this);
database = databaseHelper.getWritableDatabase();
Cursorcursor= database.execSQL(query);
It works assuming that you have a class DatabaseHelper which extends SQLiteOpenHelper
Post a Comment for "Select A Random Row In Realm Table"