1

I have a SQLite table imported in assets, trial one with 10 rows and 6 columns (_ID, QUESTION, ANSWER, OPTION1, OPTION2 AND OPTION3). I managed to read random row from database and assign that data, one question to a textview, and four possible answers to my buttons with this code:

TestAdapter mDbHelper = new TestAdapter(this);
        mDbHelper.createDatabase();

        mDbHelper.open();

        final Cursor c = mDbHelper.getTestData();

        question.setText(c.getString(1));
        bOdgovor1.setText(c.getString(2));
        bOdgovor2.setText(c.getString(3));
        bOdgovor3.setText(c.getString(4));
        bOdgovor4.setText(c.getString(5));

I also have this line in my TestAdapter class:

String sql ="SELECT * FROM tblPitanja ORDER BY RANDOM() LIMIT 1";

This is all good, but I wont randomly to assign questions to buttons, cause this way every time the answer is at button 1. How to mix questions between my buttons?

1 Answer 1

1

Put your strings into a list and use this to shuffle them around.

Here's an example:

List<String> labels = new ArrayList<String>();

labels.add(c.getString(2));
labels.add(c.getString(3));
labels.add(c.getString(4));
labels.add(c.getString(5));

Collections.shuffle(labels);

bOdgovor1.setText(labels.get(0));
bOdgovor2.setText(labels.get(1));
bOdgovor3.setText(labels.get(2));
bOdgovor4.setText(labels.get(3));
9
  • Is there a way just to upgrade this code to eliminate repeating? I don't want questions to repeat in one session. Other than that it works fine. Mar 1, 2013 at 16:42
  • Repetition should be handled in your SQL statement. Just keep the id of the questions you've asked before filter new questions by their id with WHERE statement. Mar 1, 2013 at 19:19
  • I didn't quite catch what you said. Can you give me an example? Mar 2, 2013 at 13:09
  • Just change your sql statement to String sql ="SELECT * FROM tblPitanja WHERE _id NOT IN (...) ORDER BY RANDOM() LIMIT 1"; where ... is a comma separated list of the ids you've already used. Keep in mind that you won't need to use this type of query the first time around as there is no previous question. Mar 2, 2013 at 15:12
  • Yes, but questions are drawn randomly, how can I know what ids to put there if I don't know what questions will be drawn? Mar 2, 2013 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.