D
D
Dmitry Bobreshov2018-03-30 22:00:06
Java
Dmitry Bobreshov, 2018-03-30 22:00:06

How to make random output of text by id from SQLite?

There is a DB, in it 2 columns id and the text. I can’t catch up with how to make the text output randomly by id when the button is clicked. Can anyone give me some advice or hints?
Here is the code:

//Клик по кнопке
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Random random = new Random();
                String product = "";


                Cursor cursor = mDb.rawQuery("SELECT * FROM mysovet", null);
                cursor.moveToFirst();
                while (!cursor.isAfterLast()) {
                    product = cursor.getString(1);
                    cursor.moveToNext();
                }
                cursor.close();

                textView.setText(product);

Answer the question

In order to leave comments, you need to log in

4 answer(s)
D
Developer, 2018-03-31
@is_there_something_wrong

SELECT * FROM my_table ORDER BY RANDOM() LIMIT 1;

K
key don, 2018-03-30
@keydon2

What is the actual question?
Are we not able to compose SQL queries or get a random number? Most likely we don't know how to google.
int Google = random.nextInt(count));
"SELECT text FROM table WHERE id=" + Google
where text is the name of the column with text, count is the number of fields, most likely you need to get it earlier with the query
"SELECT COUNT() FROM table"

R
Ruslan., 2018-03-31
@LaRN

You can try this:
1 we get the maximum identifier from the table, for example, with this query:
SELECT max(Id) FROM mysovet
2 we get a random number from the interval from 0 to the number obtained in step 1.
3 we get a record from the database, for example, with the following query:
Select max(Id) FROM mysovet where Id <= the number obtained in step 2.

A
AlexMDD, 2018-04-02
@AlexMDD

It is necessary to choose the optimal strategy. There is no random row selection function in SQL, so I generate an auxiliary table with random numbers. There are 2 columns in the table: 1st column is the id of the row, 2nd column is a random number. As a result of sorting this random table by 2 columns, in the first column you will have random rows from the main table. You can generate a random table before each request, or, if there are a lot of records, generate it once and with each request, run through it and remember the position where you left off. At the next request, run it from that place. When you reach the end - regenerate and start again. The previous answers may not work if your IDs are out of order. In addition, the random number generation function can often return already generated numbers. And in my method,

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question