FirebaseUI - 使用FirebaseRecyclerAdapter获取随机列表

时间:2017-06-28 12:35:51

标签: android firebase firebase-realtime-database recycler-adapter firebaseui

Firebase数据结构

{ "questions" : {
"-KkLGS71meu8aA_wcqTq" : {
  "q_answer" : "....",
  "q_category" : "....",
  "q_qid" : "1",
  "q_question" : "..."
},
"-KkLGkf8tNb-OKwu2qVa" : {
  "q_answer" : "...",
  "q_category" : "...",
  "q_qid" : "2",
  "q_question" : "..."
},
"-KkLH1T1ZhFKJaqYFuJ4" : {
  "q_answer" : "...",
  "q_category" : "...",
  "q_qid" : "3",
  "q_question" : "..."
} }

数据库引用

questionRef.orderByChild("q_qid")

如何使用FirebaseRecyclerAdapter生成随机查询和显示? 还有其他办法吗?

修改:

我试试这段代码

questionRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    long allNum = dataSnapshot.getChildrenCount();
                    int maxNum = (int)allNum;
                    int minNum = 1;
                    int randomNum = new Random().nextInt(maxNum - minNum + 1) + minNum;

                    int count = 0;
                    Iterable<DataSnapshot> ds = dataSnapshot.getChildren();
                    Iterator<DataSnapshot> ids = ds.iterator();
                    Map<String, Object> question;

                    while(ids.hasNext() && count < randomNum) {
                         question = (Map<String, Object>) ids.next().getValue();

                        String q = question.get("q_question").toString();
                        viewHolder.question.setText(q);

                        count ++; // used as positioning.
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

但有些问题出现不止一次?

1 个答案:

答案 0 :(得分:1)

您需要做的是找出数据库中可能的值public function __construct() { $this->ci =& get_instance(); $this->ci->config->load('couriers'); } 的数量,然后在以下代码行中使用它:

numVals

如果您在代码中使用迭代器迭代int random = new Random().nextInt(numVals); 而不是只是迭代一次,以获得所需的值。

希望它有所帮助。