Skip to content Skip to sidebar Skip to footer

How To Randomly Set Text To Buttons From Sqlite Without Repetition?

I have a db imported to assets, and i read from it and randomly set text to buttons and a texview, with code below: mDbHelper.open(); Cursor c = mDbHelper.getTestDat

Solution 1:

there are more approaches to solve your problem:

  1. execute the sql-statement (without limiting) at the beginning and move to the next entry of the cursor when a quesion is answered correctly
  2. buffer the questions which where already answered

the second approach could be done as follows:

first, change your method and sql, including a where-clause:

publicCursorgetTestData(String whereClause)
 {;
     try
     {
         String sql ="SELECT * FROM tblPitanja WHERE 1 = 1 " + whereClause + " ORDER BY RANDOM() LIMIT 1";
         [...]

second, buffer the already answered questions in your game-class:

add a LinkedList to your game-class

LinkedList<Long> mAnsweredQuestions = new LinkedList<Long>();

add already answered questions to the LinkedList:

Cursor c = mDbHelper.getTestData(generateWhereClause());
mAnsweredQuestions.add(c.getLong(0));
List<Answer> labels = new ArrayList<Answer>();
[...]

add a function which generates the where-clause:

privateStringgenerateWhereClause(){
    StringBuilder result = newStringBuilder();
    for (Long l : mAnsweredQuestions){
         result.append(" AND " + YOURID + " <> " + l);
    }
    return result.toString();
}

Solution 2:

You could just save the Cursor objects into an ArrayList and then use contains to find out if that question was alredy asked. (Note: contains useses the equals method)

publicclassYourClass {
     java.util.ArrayList<Long> cursorList = newjava.util.ArrayList<Long>();
     publicvoid YourMethod {

         Cursorc= mDbHelper.getTestData();
         longl= c.getLong(0);


         while(cursorList.contains(l))
         {
              Cursorc= mDbHelper.getTestData();
              l = c.getLong(0);
         }

         cursorList.add(l);

    }
}

Solution 3:

The solution depends on your application logic. One of possible solutions is to remove "LIMIT 1" from your query and load all questions randomly sorted.

If your app does something like "show me next random question I have never seen before", you have to keep the list of already visited questions (in memory, or in DB - again depends on your application logic. For DB solution is as simple as add visited column to your database.

Solution 4:

For this problem, Better you maintain the list of question(object or id) your asked. Before display any question to the user check the current question is in your array list or not. If current qus is in arraylist then you can call getTestData(), otherwise you can display the question and add id or qus object to the array list.

Post a Comment for "How To Randomly Set Text To Buttons From Sqlite Without Repetition?"