2012-10-19 41 views
2

全部 我想合乎逻辑的帮助。我有100行数据库,并获得所有行随机盟友没有重复我已经使用下面的代码。获得随机没有范围之间没有重复

public ArrayList<Rows> getRows(){ 
    ArrayList<Rows> myRaw=new ArrayList<Rows>(); 
    Cursor rawCursor=this.db.query(DB_TABLE, null, null, null, null, null, null); 
    if(rawCursor.getCount()>0){ 
     Random rng = new Random(); 
     rawCursor.moveToFirst(); 
     do { 

      // Ideally just create one instance globally 
      ArrayList<Rows> generated = new ArrayList<Raws>(); 
      for (int i = 0; i < 371; i++) 
      { 
       while(true) 
       { 
        Integer next = rng.nextInt(371) + 1; 
        rawCursor.moveToPosition(next); 
        Rows raw=new Raws(rawCursor.getInt(rawCursor.getColumnIndex("_id")),rawCursor.getString(rawCursor.getColumnIndex("raw")),rawCursor.getInt(rawCursor.getColumnIndex("fav"))); 
        if (!generated.contains(raw)) 
        { 
         // Done for this iteration 
         generated.add(raw); 
         break; 
        } 
       } 
      } 

      myRaw=generated; 

     } while (rawCursor.moveToNext()); 
     rawCursor.close(); 
    } 
    return myRaw; 
} 

感谢所有

+0

你的问题是什么?即你写的代码有什么问题? – dan1111

+2

任何不使用'ORDER BY RANDOM()'的理由? –

+1

@RenatoLochetti:好的我会但是当我提问时,我没有得到正确的答案,我怎么能接受它,因为其他开发人员可能会跟着它。 –

回答

3

您可以告诉数据库被一些random number订购的记录:

cursor = db.query(DB_TABLE, null, null, null, null, null, "random()"); 
+0

非常感谢@CL –

1

什么类别洗牌? http://developer.android.com/reference/java/util/Collections.html#shuffle(java.util.List)

public ArrayList<Rows> getRows() { 
    ArrayList<Rows> myRaw = new ArrayList<Rows>(); 
    Cursor rawCursor = this.db.query(DB_TABLE, null, null, null, null, null, null); 

    if (rawCursor.getCount() > 0) { 
     // get all the rows 
     rawCursor.moveToFirst(); 
     do { 
      Rows raw = new Raws(rawCursor.getInt(rawCursor.getColumnIndex("_id")), rawCursor.getString(rawCursor.getColumnIndex("raw")), rawCursor.getInt(rawCursor.getColumnIndex("fav"))); 
      myRaw.add(raw); 
     } while (rawCursor.moveToNext()); 
     rawCursor.close(); 
    } 
    // shuffle the rows in some kind of random order 
    Collections.shuffle(myRaw); 
    return myRaw; 
} 

由@CL提供的答案。可能是更好的选择,但主要区别在于shuffle方法有一个选项可以提供您自己的Random对象,这意味着您可以随机使用seed

//Random with seed; 
Random r = new Random(68498493); 
Collections.shuffle(myRaw, r);