3

I want to get random data from database(sqlite) without repeat.Can anyone help me ..

    DBManager *databaseManager = (DBManager *)[[DBManager alloc] init];
NSArray *array=[databaseManager readQuestionFromDatabase];
que=[array objectAtIndex:0];
self.lblQuestion.text=que.question;
[self.btnOption1 setTitle:que.questionoption1 forState:UIControlStateNormal];
[self.btnOption2 setTitle:que.questionoption2 forState:UIControlStateNormal];
[self.btnOption3 setTitle:que.questionoption3 forState:UIControlStateNormal];
[self.btnOption4 setTitle:que.questionoption4 forState:UIControlStateNormal];
ngrashia
  • 9,869
  • 5
  • 43
  • 58
Ankit Gohel
  • 77
  • 11
  • 1
    To get random row use `ORDER BY RAND()` or some faster alternative. To get unique you can remember already received rows and use something like `WHERE id NOT IN(...)`. – taro Jul 28 '14 at 07:07

2 Answers2

0

This approach using Random Number Generation via java and ROWNUM for SQLITE should help you. But you might have to execute queries multiple times.

int DBSize =  getDBSize(); 
int randomRowNum = 0;

ArrayList<Integer> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++) {
    list.add(i);
}

Random rand = new Random();
while(list.size() > 0) {
    int index = rand.nextInt(list.size());
    randomRowNum = list.remove(index);
    selQuery = "SELECT * FROM MYTABLE WHERE ROWNUM = " + randomRowNum + " ORDER BY SOME_UNIQUE_SORT_ORDER";
    // EXECUTE SELECT QUERY AND YOU WOULD GET RANDOM ROWS here.

}

private int getDBSize ()
{
    int retVal = 5;
    retVal = // Select count(1) from myTable;
    return retVal; //(Assuming I have 5 records in DB)
}

Note: Make sure your sort order in ORDER BY is unique. Else results would not be as expected.

Community
  • 1
  • 1
ngrashia
  • 9,869
  • 5
  • 43
  • 58
0

This is another answer which uses same random number generation without repetition but avoids multiple query execution.

String randomRowData = "";

selQuery = "SELECT MYFIELD FROM MYTABLE ";
ArrayList<String> list = new ArrayList<Integer>(size);
for(int i = 1; i <= size; i++) {
    list.add(MYFIELD_VALUE); // All DB Data here
}

Random rand = new Random();
while(list.size() > 0) {
    int index = rand.nextInt(list.size());
    randomRowData = list.remove(index);  // Will display the rows without repetition
    /* USE THE ROW DATA APPROPRIATELY */
}
ngrashia
  • 9,869
  • 5
  • 43
  • 58