Skip to content
Permalink
Browse files

Implementing the Like Functionality

  • Loading branch information
dragosholban committed May 13, 2018
1 parent c69233e commit 7241106eb51dbdc3410693c1dd607542fde2ba6f
@@ -88,6 +88,47 @@ public void onCancelled(DatabaseError databaseError) {
}
});

// get image likes
Query likesQuery = database.child("likes").orderByChild("imageId").equalTo(image.key);
likesQuery.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Like like = dataSnapshot.getValue(Like.class);
image.addLike();
if(like.userId.equals(fbUser.getUid())) {
image.hasLiked = true;
image.userLike = dataSnapshot.getKey();
}
mAdapter.notifyDataSetChanged();
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Like like = dataSnapshot.getValue(Like.class);
image.removeLike();
if(like.userId.equals(fbUser.getUid())) {
image.hasLiked = false;
image.userLike = null;
}
mAdapter.notifyDataSetChanged();
}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {

}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

mAdapter.addImage(image);
}

@@ -167,4 +208,21 @@ public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
});
}
}

public void setLiked(Image image) {
if(!image.hasLiked) {
// add new Like
image.hasLiked = true;
Like like = new Like(image.key, fbUser.getUid());
String key = database.child("likes").push().getKey();
database.child("likes").child(key).setValue(like);
image.userLike = key;
} else {
// remove Like
image.hasLiked = false;
if (image.userLike != null) {
database.child("likes").child(image.userLike).removeValue();
}
}
}
}
@@ -53,6 +53,19 @@ public void onBindViewHolder(ViewHolder holder, final int position) {
holder.mTextView.setText(image.user.displayName);
}
Picasso.get().load(image.downloadUrl).into(holder.mImageView);

holder.mLikeButton.setText("Like (" + image.likes + ")");
if(image.hasLiked) {
holder.mLikeButton.setBackgroundColor(mActivity.getResources().getColor(R.color.colorAccent));
} else {
holder.mLikeButton.setBackgroundColor(mActivity.getResources().getColor(R.color.colorPrimary));
}
holder.mLikeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mActivity.setLiked(image);
}
});
}

// Return the size of your dataset (invoked by the layout manager)

0 comments on commit 7241106

Please sign in to comment.
You can’t perform that action at this time.