在我的SQLite数据库中,我在KEY_ALCOHOL列中提取了所有“Liquor”条目,如何从所选组中选择一个随机条目?
以下是我如何获得小组:
public Cursor getAlcohol(String alcohol) throws SQLException
{
Cursor mCursor =
myDataBase.query(true, DB_TABLE, new String[] {
KEY_ROWID,
KEY_ALCOHOL,
KEY_TYPE,
KEY_BRAND,
KEY_PRICE
},
KEY_ALCOHOL + "=?",
new String[] { alcohol },
null,
null,
null,
null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
这会返回大约60个不同的条目,我需要随机选择一个。
这是对数据库助手.java的第二次尝试
public Cursor getTest(String test) throws SQLException
{
Cursor mCursor =
myDataBase.query(true, DB_TABLE, new String[] {
KEY_ROWID,
KEY_ALCOHOL,
KEY_TYPE,
KEY_BRAND,
KEY_PRICE
},
KEY_ALCOHOL + "=?",
new String[] { test },
null,
null,
"RANDOM()",
"LIMIT 1");
return mCursor;
}
这就是我在主要活动中称呼它的方式:
myDbHelper.openDataBase();
Cursor c = myDbHelper.getTest("Liquor");
if (c.moveToFirst())
{
do {
DisplayTitle(c);
} while (c.moveToNext());
}
myDbHelper.close();
}
public void DisplayTitle(Cursor c)
{
Toast.makeText(this,
"id: " + c.getString(0) + "\n" +
"ALCOHOL: " + c.getString(1) + "\n" +
"TYPE: " + c.getString(2) + "\n" +
"BRAND: " + c.getString(3) + "\n" +
"PRICE: " + c.getString(4),
Toast.LENGTH_LONG).show();
}
答案 0 :(得分:1)
您需要添加
ORDER BY RANDOM() LIMIT 1;
到你的查询。所以试试这个(未经测试):
myDataBase.query(true, DB_TABLE, new String[] {
KEY_ROWID,
KEY_ALCOHOL,
KEY_TYPE,
KEY_BRAND,
KEY_PRICE
},
KEY_ALCOHOL + "=?",
new String[] { alcohol },
null,
null,
"RANDOM()",
"LIMIT 1");
答案 1 :(得分:0)
获取mCursor.getCount()
的大小,随机选择一个0以内的数字并计数(请参阅How do I generate random integers within a specific range in Java?),然后使用mCursor.moveToPosition(randomInt)
移动mCursor,得到行,我建议。