我如何检索随机值Firebase数据库 [英] how can i retrieve a random value Firebase database
本文介绍了我如何检索随机值Firebase数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个firebase数据库,其树看起来像这样
I have a firebase database with a tree that looks like this
tvthemetunes
airwolf value "url to air wolftheme"
eastenders value "url to eastenders"
knight rider value "url to nightrider"
依旧...
在我的应用用户下载项目,而下载电视主题的项目将从网址播放。我可以让它在单个项目的值事件时正常工作。我希望它从列表中随机选择一个值。怎么能实现这个?
in my app users download items and while items download a tv theme will play from the url. i can get it to work ok when value event for a single item. i want it to pick a value at random from the list. how can achieve this?
编辑可以使用回收查看方法,因为我的应用程序不包含任何
Edit can use recycle view method as my app does not contain any
这是我的单项代码
protected Dialog onCreateDialog(int id) {
switch (id) {
case progress_bar_type:
//Here is where i play the theme
getthemetune();
pDialog = new ProgressDialog(c);
pDialog.setTitle(MY Title);
pDialog.setMessage(MY Message);
pDialog.setIcon(R.mipmap.ic_launcher);
pDialog.setIndeterminate(false);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
return pDialog;
default:
return null;
}
}
private void getthemetune(){
mthemetuneref = FirebaseDatabase.getInstance();
DatabaseReference ref = mthemetuneref.getReference().child(MYREF);
ref.child("airwolf").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Edit to add Alex's answer?
long childrenCount = datasnapshot.getChildrenCount();
int count = (int) childrenCount;
//Dont know how to use this
int randomNumber = new Random().nextInt(count);
plysound();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void plysound(){
mp = new MediaPlayer();
String j =
tvThemeTune.toString();
Log.i("Url",j);
try {
mp.setDataSource(j);
} catch (IOException e) {
e.printStackTrace();
}
try {
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
mp.start();
Log.i("Sound playing", "Ok");
mp.setLooping(true);
}
推荐答案
要解决此问题,请使用以下代码行:
To solve this, please use the following lines of code:
long childrenCount = snapshot.getChildrenCount();
int count = (int) childrenCount;
int randomNumber = new Random().nextInt(count);
然后使用 for
循环使用随机数拉取该值:
And then use a for
loop to pull that value using the random number:
int i=0;
String themeTune; //Your random themeTune will be stored here
for (DataSnapshot snap : snapshot.getChildren()) {
if(i = randomNumber) {
themeTune = snap.getValue(String.class);
break;
}
i++;
}
plysound();
这篇关于我如何检索随机值Firebase数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文