RecylerView Adapter in android Firebase is not qui

2019-07-20 15:35发布

问题:

I am creating a program, where user can update post, and other user and same user can react there. For that, I have implemented the love button. So this works this way, I have saved a unique id in the DatabaseReference and other reference for uniquekey for easiness. So, whenever, the user clicks on love button, it must update the total reaction of the node by increasing it to one. The problem I am getting is, whenever I press the love button key, it doesn't call the uniqueID I need. The uniqueId I am getting from model class from viewholder is not the post I have reacted to.

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);
            }

        }
    }

}