从两个不同的Firebase节点检索并设置RecyclerView数据

时间:2017-09-04 21:40:30

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

我的主要目标是将RecyclerView项目设置为" favited"基于用户之前的动作。我可以在点击时存储和删除这些数据,但我很难在正确的时间将其显示在正确的位置。

我有两个不同的节点可供我实现:

"quotes" : {
   "0" : {
      "Name" : "Foo",
      "Source" : "Bar" },
   "1" : {
      "Name" : "Foo",
      "Source" : "Bar" },
   "2" : {
      "Name" : "Foo",
      "Source" : "Bar" }
   },

"favorites" : {
   "blah@blah,com" : {
      "uid0" : "0"
      "uid1" : "2" }}}

基本上我正在尝试做的事情: 显示RecyclerView中的所有引号,如果它们的ID显示在该唯一用户的收藏夹中,则将其视觉设置为收藏夹。我在这里包含了一些似乎不适合我的代码。

private void bindHeart(final ItemHeartCardBinding binding) {
        if (inProgress) {
            animateProgress(binding);
        } else {
            binding.favorite.setImageResource(R.drawable.favorite_state_list);
        }
        //Loop through users favorites to see if current item exists
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
        String email = "";
        if (user != null) {
            email = user.getEmail();
            email = email.replace(".", ",");
        }

        final DatabaseReference favoriteRef = mRootRef.child("favorites/" + email);

        //quoteKeyStringResId is passed in here as each RecyclerView item is being created. It's the uid of each quote.
        final Query queryRef = favoriteRef.orderByValue().startAt(quoteKeyStringResId).endAt(quoteKeyStringResId);

        queryRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                if (dataSnapshot.getValue().toString().equals(quoteKeyStringResId)) {
                    binding.favorite.setChecked(checked);
                } else {
                    binding.favorite.setChecked(!checked);
                }
}

1 个答案:

答案 0 :(得分:0)

我挖掘了Firebase database samples,发现了一种更好的数据建模方法。在同一节点中包含所有相关数据允许我同时查询所有数据,而不必担心将RecyclerView项目保持在相同的顺序。事情并非如此浅薄,但我认为没关系:

"quotes" : {
   "0" : {
      "Name" : "Foo",
      "Source" : "Bar",
      //Moved this from a separate node into here
      "Favorites" : {
          //Each user will be listed if favorited, and removed if unfavorited, making it easy to track and get totals
          "userUid" : "true",
          "userUid4" : "true" }},
   "1" : {
      "Name" : "Foo",
      "Source" : "Bar" },
   "2" : {
      "Name" : "Foo",
      "Source" : "Bar",
      "Favorites" : {
          "userUid" : "true" }
   }}