【问题标题】:How to fetch random data from Firebase from Parent and its children [duplicate]如何从父级及其子级的 Firebase 中获取随机数据 [重复]
【发布时间】:2021-11-07 22:37:40
【问题描述】:

我想显示随机图像,来自firebase实时数据库的报价(数据),就像按asc,desc,RAND()的sql数据库顺序一样。

如何通过简短的代码来完成这个 firebase 实时数据库。

databaseReference = FirebaseDatabase.getInstance().getReference().child("Quotes").orderby ????;

【问题讨论】:

    标签: android database firebase firebase-realtime-database


    【解决方案1】:

    以下是随机获取数据的一种方法,但它并不完美, Reference for this code by peter(answer)

    databaseReference = FirebaseDatabase.getInstance().getReference().child("Quotes");
    databaseReference .addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int ads = (int) dataSnapshot.getChildrenCount();
                int rand = new Random().nextInt(ads);
                for(DataSnapshot data: dataSnapshot.getChildren()){
                for(DataSnapshot datas: data.getChildren()){
                for(int i = 0; i < rand; i++) {
        
                list = new ArrayList<your-class-method-for-holding data>();
        
                    Yourclass value = datas.getValue(yourclass.class);
                    //Use your class to get the data and display it on your views
                    //in this loop  
                    
        
        }}}}
    

    【讨论】:

      猜你喜欢
      • 2020-06-20
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      相关资源
      最近更新 更多