过滤查询以填充FirebaseRecyclerAdapter

时间:2017-01-11 23:19:07

标签: android firebase firebase-realtime-database firebaseui

目前还不清楚如何使用自定义查询填充FirebaseRecyclerAdapter。

  1. 定义参考。这里:DatabaseReference ref = mDatabase.getReference().child("users");

  2. 将其发送到适配器initAdapter(ref);

  3. 定义查询并设置侦听器。是不是?

    mAdapter = new FirebaseRecyclerAdapter<User, UserHolder>(User.class,  R.layout.user_row_layout, UserHolder.class, ref) {
    
            @Override
            protected void populateViewHolder(final UserHolder viewHolder, final User model, int position) {
    
                Query query = ref.orderByChild("group").equalTo(uid);
                query.addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                        viewHolder.setName(model.getName());
                        viewHolder.setStatus(getStatus(model.getStatus()));
                    }
    
                    // ...
                };
    
  4. 仍然显示来自用户的所有数据。只需要根据uid进行过滤。有线索吗?

2 个答案:

答案 0 :(得分:3)

对于那些可能试图让事情变得过于复杂或者晚上工作的人来说,这里有解决方案:

mAdapter = new FirebaseRecyclerAdapter<User, UserHolder>(
               User.class,  
               R.layout.user_row_layout, 
               UserHolder.class,
               ref.orderByChild("group").equalTo(uid)
) {
    @Override
    protected void populateViewHolder(final UserHolder viewHolder, final User model, int position) {

                viewHolder.setName(model.getName());
                viewHolder.setStatus(getStatus(model.getStatus()));
            }

            // ...
        };

晁!

答案 1 :(得分:0)

一个简单示例,其中显示了所有用户的排名列表:

FirebaseRecyclerAdapter<UserData,RankListViewHolder> adapter = new FirebaseRecyclerAdapter<UserData, RankListViewHolder>
                (
           UserData.class,
           R.layout.rank_item,
           RankListViewHolder.class,
           userRef.child("users").getRef() //--Set here your query
                )
        {
            @Override
protected void populateViewHolder(RankListViewHolder viewHolder, UserData model, int position)
            {
                viewHolder.tvPos.setText(""+position+"º");
                viewHolder.userId = model.getId();
            }
        };