0

I've tried everything and looked at these questions (one, two, three(vid tut)) for answers and tried them, but still to no avail am I able to set the childrencount that I can clearly see in the logs using an int into a textview.

public class HomeListAdapter extends RecyclerView.Adapter<HomeListAdapter.ViewHolder> {
    private static final String TAG = HomeListAdapter.class.getSimpleName();
    private DatabaseReference mDatabase;
    private Context context;
    private List<Recipe> mRecipesList;
    private MainActivity mainActivity;
    private ProgressBar progressBar;
    private int likeCounter = 0;

    public HomeListAdapter(Context context, List<Recipe> mRecipesList) {
        this.context = context;
        this.mRecipesList = mRecipesList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_recipes_recipe_item, parent, false);

        mDatabase = FirebaseDatabase.getInstance().getReference();
        mainActivity = (MainActivity) view.getContext();
        progressBar = mainActivity.findViewById(R.id.main_progressBar);

        return new HomeListAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        final Recipe recipe = mRecipesList.get(position);
        SetUserData(holder, position);
        holder.tv_recipe_title.setText(mRecipesList.get(position).getTitle());
        holder.tv_recipe_prepTime.setText(mRecipesList.get(position).getPrepTime());


        Glide.with(context).load(mRecipesList.get(position).getUrl())
                .placeholder(R.drawable.ic_loading).thumbnail(0.05f).fitCenter()
                .transition(DrawableTransitionOptions.withCrossFade()).centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .into(holder.recipe_thumbnail);

        Log.i(TAG, "onBindViewHolder: Database Reference = " + mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid()).child(Constants.DATABASE_ROOT_LIKES));
        mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid()).child(Constants.DATABASE_ROOT_LIKES).addValueEventListener(new ValueEventListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                likeCounter = (int) dataSnapshot.getChildrenCount();
                Log.i(TAG, "onDataChange: ChildrenCount = " + recipe.getTitle() + " " + likeCounter);
                holder.tv_like_counter.setText(Integer.toString(likeCounter));
            }


            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });

        mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid())
                .child(Constants.DATABASE_ROOT_LIKES).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.hasChild(getUid())){
                    holder.like.setLiked(true);
                    Log.i(TAG, "onDataChange: LIKED RECIPE...");
                }else{
                    Log.i(TAG, "onDataChange: RECIPE IS NOT LIKED...");
                    holder.like.setLiked(false);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid())
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        if(dataSnapshot.hasChild(Constants.DATABASE_RECIPE_LIKE_COUNT_VALUE)){
                            holder.tv_like_counter.setText(String.valueOf(dataSnapshot.child(Constants.DATABASE_RECIPE_LIKE_COUNT_VALUE).getValue()));
                        }else{
                            holder.tv_like_counter.setText("0");
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
        holder.like.setOnLikeListener(new OnLikeListener() {
            @Override
            public void liked(LikeButton likeButton) {
                Log.i(TAG, "liked: LIKED");
                // Add like
                holder.like.setLiked(true);
                Log.i(TAG, "CheckLikeStatus: " + recipe.title + " " + recipe.hasLiked);
                mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid()).child(Constants.DATABASE_ROOT_LIKES).child(getUid()).setValue("true");

            }

            @Override
            public void unLiked(LikeButton likeButton) {
                Log.i(TAG, "unLiked: UNLIKED");
                // remove Like
                holder.like.setLiked(false);
                Log.i(TAG, "CheckLikeStatus: " + recipe.title + " " + recipe.hasLiked);
                mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid()).child(Constants.DATABASE_ROOT_LIKES).child(getUid()).removeValue();

                }

        });

    }

    private void SetUserData(ViewHolder holder, int position) {
        mDatabase.child(Constants.DATABASE_ROOT_USERS).child(mRecipesList.get(position).getCreatorId())
                .addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        User user = dataSnapshot.getValue(User.class);
                        holder.tv_user_username.setText(user.getUsername());
                        Glide.with(context).load(user.getUrl()).centerCrop().placeholder(R.drawable.ic_loading).into(holder.userPhoto);
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });
    }

    @Override
    public int getItemCount() {
        return mRecipesList.size();
    }


    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView tv_recipe_title, tv_recipe_prepTime, tv_user_username, tv_like_counter;
        public ImageView recipe_thumbnail;
        public LikeButton like;
        public CircleImageView userPhoto;
        public LinearLayout user_ll;
        public FirebaseAuth mAuth;
        public FirebaseDatabase mDatabase;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            mainActivity = (MainActivity) itemView.getContext();
            mDatabase = FirebaseDatabase.getInstance();
            tv_recipe_title = itemView.findViewById(R.id.recipe_item_title);
            tv_recipe_prepTime = itemView.findViewById(R.id.recipe_item_time);
            recipe_thumbnail = itemView.findViewById(R.id.recipe_item_photo);
            like = itemView.findViewById(R.id.recipe_item_image_like);
            tv_like_counter = itemView.findViewById(R.id.recipe_item_like_counter);
            userPhoto = itemView.findViewById(R.id.recipe_item_user_photo);
            tv_user_username = itemView.findViewById(R.id.recipe_item_user_username);
            user_ll = itemView.findViewById(R.id.recipe_item_user_linearLayout);

            user_ll.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    ProfileFragment pf = new ProfileFragment();
                    if(pf.isAdded()){
                        return;
                    }else{
                        Bundle bundle = new Bundle();
                        bundle.putString(Constants.EXTRA_USER_UID,mRecipesList.get(getAdapterPosition()).getCreatorId());
                        Log.i(TAG, "onClick: Fragment Interaction recipe Creator Id = " + mRecipesList.get(getAdapterPosition()).getCreatorId());
                        FragmentTransaction ft = mainActivity.getSupportFragmentManager().beginTransaction();
                        pf.setArguments(bundle);
                        ft.replace(R.id.main_frame, pf, Constants.FRAGMENT_TAG_PROFILE);
                        ft.addToBackStack(Constants.FRAGMENT_TAG_PROFILE);
                        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                        ft.commit();
                    }
                }
            });

            itemView.setOnClickListener(v -> {
                RecipeDetailsFragment rd = new RecipeDetailsFragment();
                if(rd.isAdded()){
                    return;
                }else{
                    Bundle bundle = new Bundle();
                    bundle.putString(Constants.EXTRA_RECIPE_KEY,mRecipesList.get(getAdapterPosition()).getUid());
                    bundle.putString(Constants.EXTRA_RECIPE_CREATOR_ID, mRecipesList.get(getAdapterPosition()).getCreatorId());
                    Log.i(TAG, "onClick: Fragment Interaction recipe Key is = " + mRecipesList.get(getAdapterPosition()).getUid());
                    FragmentTransaction ft = mainActivity.getSupportFragmentManager().beginTransaction();
                    rd.setArguments(bundle);
                    ft.replace(R.id.main_frame, rd, Constants.FRAGMENT_TAG_RECIPE_DETAILS);
                    ft.addToBackStack(null);
                    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
                    ft.commit();
                }
            });
        }

    }

    public String getUid() {
        return FirebaseAuth.getInstance().getCurrentUser().getUid();
    }
    }

enter image description here

enter image description here

enter image description here

Molly
  • 1,887
  • 3
  • 17
  • 34
wesley franks
  • 6,765
  • 4
  • 16
  • 29

3 Answers3

0

So, after checking the logs, it is very clear that there is nothing wrong with the Firebase. But, there is something wrong with your view binding process with the adapter. The tutorials which you are following right now, is not going to help, since everything is okay on the firebase side.

The problem is, that when you are calling holder.tv_like_counter.setText(Integer.toString(likeCounter)); , tv_like_counter is not even prepared yet.

It would be great if you can show how you are binding your views in the adapter. If not, you can also refer this link to solve your problem. At Least now you know in which direction you need to search ;)

Vishal Roy
  • 70
  • 1
  • 10
0

I did a bit more of a different perspective look after checking the view bindings. I found that there was a contradiction. See below:

mDatabase.child(Constants.DATABASE_ROOT_RECIPES).child(recipe.getUid())
            .addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.hasChild(Constants.DATABASE_RECIPE_LIKE_COUNT_VALUE)){
                        holder.tv_like_counter.setText(String.valueOf(dataSnapshot.child(Constants.DATABASE_RECIPE_LIKE_COUNT_VALUE).getValue()));
                    }else{
                        // likes do not exist
                        holder.tv_like_counter.setText("0");
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

I removed holder.tv_like_counter.setText("0");. It's supposed to only set it to 0 if the snapshot didn't have the child. I simply forgot the logic I had in place when I was troubleshooting.

enter image description here

wesley franks
  • 6,765
  • 4
  • 16
  • 29
0

Don't do fetching data from database operation inside the onBindViewHolder, It is a very bad practice and data calls will be created every time when the view comes to display.

And it won't be completed that's why you did not get the output. because before getting output it may be destroyed.

Do whole data related operations inside your Activity and pass the data to Adapter.

See this

Happy coding !!!

majurageerthan
  • 2,169
  • 3
  • 17
  • 30