How to randomly populate a fragment with database data

118 views Asked by At

I have a fragment that displays data gotten from a database(sqlite) row. What I want to achieve now is to pic a different row from the database and populate the fragment on a button click. If possible, I would like the row to be picked randomly. I hope I asked the question Right. Thanks in advance

1

There are 1 answers

0
Karakuri On BEST ANSWER

One possible way is to query for all the rows at once with random order and keep the cursor around. Then every time the button is clicked, just advance the cursor position and use that data. When you run out of rows, you can query again to get another randomized cursor and repeat.

I'm not sure what your query code looks like, but what you want is essentially

SELECT [columns] FROM [table] ORDER BY random();

The important part is the ORDER BY random().

Note that this strategy will not allow the same row data to appear a second time unless you exhaust the entire cursor once. If that's not acceptable, then the next possibility is to query every time the button is clicked and do something like this:

SELECT [columns] FROM [table] WHERE _id != [current_item_id] ORDER BY random() LIMIT 1;

Whatever your primary key column is (my example uses _id), make the query exclude the row whose value is the same as the current item. Order by random() again and limit by 1 to return just 1 row.