>有人知道在MySQL中显示数据库中的随机数据并在listview中显示吗?
我可以不随机显示所有数据,但我想随机显示,有人可以帮忙吗?
我的代码 :
for (int i = 0; i < response.length() ; i++) {
try {
JSONObject obj = response.getJSONObject(i);
Exercise exercise = new Exercise();
if (obj.getString("KindOf").equals(textKind.getText().toString()) && obj.getString("Type").equals("Strength")) {
exercise.setTipe(obj.getString("Type"));
exercise.setJenis(obj.getString("KindOf"));
exercise.setNama(obj.getString("Name"));
exerciseList.add(exercise);
} catch (JSONException e) {
e.printStackTrace();
}
}
如果要洗牌 ArrayList,只需使用 Collections shuffle
方法即可。
Collections.shuffle(exerciseList);
或
SELECT *
FROM excercises
ORDER BY RAND();
如果您希望它在数据库级别。
创建一个随机数
Random rand = new Random();
int n = rand.nextInt(exerciseList.size());
然后使用随机数作为索引,从练习列表中获取一个项目,并将其添加到新数组中(如果它尚不存在)。
要随机使用ArrayList,您只需使用Collections shuffle方法即可。
Collections.shuffle(exerciseList);
或者,当您从数据库访问数据时,您可以在 Web 服务方法中使用随机函数。