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;
}

谢谢大家

4

2 回答 2

3

您可以告诉数据库按一些随机数对记录进行排序:

cursor = db.query(DB_TABLE, null, null, null, null, null, "random()");
于 2012-10-19T12:27:12.213 回答
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对象,这意味着您可以随机播种。

//Random with seed;
Random r = new Random(68498493);
Collections.shuffle(myRaw, r);
于 2012-10-19T12:27:57.437 回答