从我的 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();
}