如何从 Firebase 数据库中检索随机值?

mar*_*rop 2 java android firebase

我有一个带有看起来像这样的树的 firebase 数据库

tvthemetunes
airwolf value "url to air wolftheme"
eastenders value "url to eastenders"
knight rider value "url to nightrider"
Run Code Online (Sandbox Code Playgroud)

等等...

在我的应用程序中,用户下载项目,当项目下载时,将从 url 播放电视主题。当单个项目的值事件时,我可以让它正常工作。我希望它从列表中随机选择一个值。怎样才能做到这一点?

编辑可以使用回收视图方法,因为我的应用程序不包含任何

这是我的单个项目代码

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);
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*amo 6

要解决此问题,请使用以下代码行:

long childrenCount = snapshot.getChildrenCount();
int count = (int) childrenCount;
int randomNumber = new Random().nextInt(count);
Run Code Online (Sandbox Code Playgroud)

然后使用for循环使用随机数提取该值:

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();
Run Code Online (Sandbox Code Playgroud)