【问题标题】:How can I retrieve a random value from Firebase database?如何从 Firebase 数据库中检索随机值?
【发布时间】:2018-01-14 00:43:20
【问题描述】:

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

tvthemetunes
airwolf value "url to air wolftheme"
eastenders value "url to eastenders"
knight rider value "url to nightrider"

等等……

在我的应用程序中,用户下载项目,当项目下载时,电视主题将从 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);
}

【问题讨论】:

  • 如果不是很多,做一些更详细的事情,说如果随机整数是n,下载相应的东西。否则,获取列表中的所有 url 并在列表中选择一个随机元素。 Firebase 不会有任何内置函数来从树的某个部分获取随机元素,如果这是您要查找的内容。
  • 请看这个answer

标签: java android firebase


【解决方案1】:

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

long childrenCount = snapshot.getChildrenCount();
int count = (int) childrenCount;
int randomNumber = new Random().nextInt(count);

然后使用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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-25
    • 2018-09-10
    • 2017-07-06
    • 2018-07-26
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多