Android Firebase中的RecylerView Adapter并不完全同步

时间:2018-01-04 06:49:41

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

我正在创建一个程序,用户可以在其中更新帖子,其他用户和同一用户可以在那里做出反应。为此,我实施了爱情按钮。所以这样工作,我已经在DatabaseReference中保存了一个唯一的id,并为easykey保存了uniquekey的其他参考。因此,每当用户点击爱情按钮时,它必须通过将节点增加到一个来更新节点的总反应。我得到的问题是,每当我按下爱情按钮键时,它都不会调用我需要的唯一ID。我从viewholder获取的modelId的uniqueId不是我反应的帖子。

public class LatestFragment extends Fragment {
        private RecyclerView latestFragmentRecyclerView;
        private DatabaseReference mDatabaseReference;
        private FirebaseAuth mAuth;
        private static Context context;
        private static boolean firstTime;
        private static String totalVotes;
        private static String uniqueKey;
        private static DatabaseReference reactionDatabaseReference;
        private static DatabaseReference uniqueKeysReferences;
        private static Boolean userReactState;
        private static List<String> allUniqueKeys;


    public LatestFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_latest,container,false);
        latestFragmentRecyclerView = (RecyclerView) v.findViewById(R.id.recyclerViewForLatestFragment);
        latestFragmentRecyclerView.setHasFixedSize(true);
        userReactState = false;
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setReverseLayout(true);
        layoutManager.setStackFromEnd(true);

        latestFragmentRecyclerView.setLayoutManager(layoutManager);
        mAuth = FirebaseAuth.getInstance();
        mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Posts");
        reactionDatabaseReference=FirebaseDatabase.getInstance().getReference().child("PostReactions");
        uniqueKeysReferences = FirebaseDatabase.getInstance().getReference().child("UniqueKeys");

        mDatabaseReference.keepSynced(true);
        firstTime = true;

        return v;
    }

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

        final FirebaseRecyclerAdapter<Posts, PostViewHolder> firebaseRecyclerAdapter =
                new FirebaseRecyclerAdapter<Posts, PostViewHolder>(
                        Posts.class, R.layout.each_post_layout, PostViewHolder.class, mDatabaseReference
                ) {


                    @Override
                    protected void populateViewHolder(final PostViewHolder viewHolder,final Posts model, int position) {
                        Context c = getActivity();
                        context = c;
                        uniqueKey = model.getUnique();
                        viewHolder.setUsername(model.getUsername());
                        viewHolder.setCaption(model.getCaption());
                        viewHolder.setTime(model.getTime());
                        viewHolder.setImage(model.getImage(),c);
                        viewHolder.setCurrentUserImage(model.getUserPhoto(),c);
                        viewHolder.imageViewIfUserClicked(model.getCurrentUserReaction(),c);
                         totalVotes = model.getTotalReactions();


                    }

                };

        latestFragmentRecyclerView.setAdapter(firebaseRecyclerAdapter);


    }

    public static class PostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        View theRecyclingView;
        private Button loveButton ;

        public PostViewHolder(View itemView) {
            super(itemView);
            theRecyclingView = itemView;
            loveButton = (Button) theRecyclingView.findViewById(R.id.loveButton);
            loveButton.setOnClickListener(this);

        }


        @Override
        public void onClick(View view) {
            if(view.getId()==loveButton.getId())
            {
                allUniqueKeys = new ArrayList<>();
               int position = getAdapterPosition();
               Log.e("UniqueKey", String.valueOf(position));
               uniqueKeysReferences.addValueEventListener(new ValueEventListener() {
                   @Override
                   public void onDataChange(DataSnapshot dataSnapshot) {

                       for (DataSnapshot x : dataSnapshot.getChildren()) {

                       }
                   }

                   @Override
                   public void onCancelled(DatabaseError databaseError) {

                   }
               });



                if(firstTime==true)
                {


                    loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button_red,0,0,0);
                    firstTime = false;

                    int vote= Integer.valueOf(totalVotes);
                    vote++;
                    totalVotes = String.valueOf(vote);

                    reactionDatabaseReference.child(uniqueKey).child("TotalReactions").setValue(totalVotes).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if(task.isSuccessful())
                            {
                                reactionDatabaseReference.child(uniqueKey).child("CurrentUserReaction").setValue("true").addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if(task.isSuccessful())
                                        {

                                        }
                                        else
                                        {
                                            Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                            }
                            else
                            {
                                Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
                            }
                        }
                    });


                }
                else
                {
                    loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button,0,0,0);
                    firstTime = true;

                    int vote= Integer.valueOf(totalVotes);
                    vote--;
                    totalVotes = String.valueOf(vote);

                    reactionDatabaseReference.child(uniqueKey).child("TotalReactions").setValue(totalVotes).addOnCompleteListener(new OnCompleteListener<Void>() {
                        @Override
                        public void onComplete(@NonNull Task<Void> task) {
                            if(task.isSuccessful())
                            {
                                reactionDatabaseReference.child(uniqueKey).child("CurrentUserReaction").setValue("false").addOnCompleteListener(new OnCompleteListener<Void>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Void> task) {
                                        if(task.isSuccessful())
                                        {

                                        }
                                        else
                                        {
                                            Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
                                        }
                                    }
                                });
                            }
                            else
                            {
                                Toast.makeText(context," Some Error Occured ",Toast.LENGTH_LONG).show();
                            }
                        }
                    });
                }

            }
        }

        public void setUsername(String username)
        {
            TextView mUsername= (TextView) theRecyclingView.findViewById(R.id.userWhoPostedUserName);
            mUsername.setText(username);
        }


        public void setCaption(String caption) {
            TextView mUsername= (TextView) theRecyclingView.findViewById(R.id.captionForPic);
            mUsername.setText(caption);
        }

        public void setImage(final String image, final Context c) {
            final ImageView imageView = (ImageView) theRecyclingView.findViewById(R.id.userUploadedImageView);

            Picasso.with(c).load(image).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onError() {
                Picasso.with(c).load(image).into(imageView);
                }
            });
        }

        public void setTime(String time) {
            TextView time_of_posting = (TextView) theRecyclingView.findViewById(R.id.timeOfPosting_each_post_layout);
            time_of_posting.setText(time);
        }

        public void setCurrentUserImage(final String userPhoto, final Context c) {
            final CircleImageView imageView = (CircleImageView) theRecyclingView.findViewById(R.id.userWhoPostedCircleImageView);

            Picasso.with(c).load(userPhoto).networkPolicy(NetworkPolicy.OFFLINE).into(imageView, new Callback() {
                @Override
                public void onSuccess() {

                }

                @Override
                public void onError() {
                    Picasso.with(c).load(userPhoto).into(imageView);
                }
            });
        }


        public void imageViewIfUserClicked(String currentUserReaction, final Context c) {

            //reactionDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
              //  @Override
                //public void onDataChange(DataSnapshot dataSnapshot) {
                  //  String CurrentuserReaction = dataSnapshot.child(uniqueKey).child("TotalReactions").child("CurrentUserReaction").getValue().toString();
                    // userReactState = Boolean.parseBoolean(CurrentuserReaction);
                //}

                //@Override
                //public void onCancelled(DatabaseError databaseError) {
//
  //              }
    //        });

            if(userReactState==false) {

                loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button,0,0,0);
            }
            else
            {
                loveButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.like_button_red,0,0,0);
            }

        }
    }

}

0 个答案:

没有答案