如何在新的Firebase数据库引用中进行排序(Recyclerview)

时间:2016-10-28 23:22:24

标签: android firebase android-recyclerview firebase-realtime-database

我从用户名结构中提取数据,我想按名称或用户名排序。这是否可以使用新的firebase数据库引用。我一直在四处寻找,我找不到任何关于它的信息。

这是我的代码:

databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");

}

@Override
protected void onStart() {
    super.onStart();

    FirebaseRecyclerAdapter<addFriends,addFriendsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<addFriends, addFriendsViewHolder>(
            addFriends.class,
            R.layout.addfriends_row,
            addFriendsViewHolder.class,
            databaseReference
    ) {
        @Override
        protected void populateViewHolder(addFriendsViewHolder viewHolder, addFriends model, int position) {
            viewHolder.setName(model.getName());
            viewHolder.setUsername(model.getUsername());
        }
    };
    addfriendsRecyclerView.setAdapter(firebaseRecyclerAdapter);
}

这是我在firebase中的结构:

{
  "asdadafdsgsaasfsa" : {
    "name" : "juanito",
    "username" : "cacadeperro22"
  },
  "dasdsadadaf" : {
    "name" : "cucu",
    "username" : "dsadadas"
  },
  "dsadasddsa" : {
    "name" : "username",
    "username" : "pisad"
  },
  "dsdsada" : {
    "name" : "name",
    "username" : "username"
  },
  "qUYxycDlMwYZ6r2WSA1TAacbdPh1" : {
    "email" : "elvis0288@hotmail.com",
    "name" : "Elvis De Abreu",
    "username" : "elvis0288"
  },
  "qadfdafa" : {
    "name" : "Josue Caca",
    "username" : "chupapenes"
  },
  "x123" : {
    "name" : "fsf",
    "username" : "dadfasfd"
  },
  "xxxxxx" : {
    "name" : "123",
    "username" : "culo"
  }
}

谢谢!

1 个答案:

答案 0 :(得分:8)

编辑:已经离开并回来完成回答。看到有人打败了我:) 传入FirebaseRecyclerAdapter构造函数中的QueryRef而不是数据库引用。

databaseReference = FirebaseDatabase.getInstance().getReference().child("Users");

// ...

@Override
protected void onStart() {
    super.onStart();

Query query = databaseReference.orderByChild("name"); // or ...orderByChild("username");
FirebaseRecyclerAdapter<addFriends,addFriendsViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<addFriends, addFriendsViewHolder>(
        addFriends.class,
        R.layout.addfriends_row,
        addFriendsViewHolder.class,
        query
) {
    @Override
    protected void populateViewHolder(addFriendsViewHolder viewHolder, addFriends model, int position) {
        viewHolder.setName(model.getName());
        viewHolder.setUsername(model.getUsername());
    }
};
addfriendsRecyclerView.setAdapter(firebaseRecyclerAdapter);
}