簡體   English   中英

如何從Firebase數據庫檢索隨機值?

[英]How can I retrieve a random value from Firebase database?

我有一個帶有這樣的樹的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);
}

要解決此問題,請使用以下代碼行:

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM