I am trying to make app like Instagram with Firebase as a backend, while user adds the comment in any photo, new id is generated by Firebase now I want to add one child(likes) when user click on the like button in this randomly generated comment id but the issue is how to get that particular comment id?
2 Answers
There are two ways in which you can achieve this. So if you want to access a specific comment, you must know something that unique identifies that pcommentll. The first solution would be to store that random id in a variable in the exact moment when you are pushing a new comment to the database using the push()
method. To get that id, you can use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String commentId = rootRef
.child(UserId)
.child(PhotoId)
.child("comments")
.push()
.getKey();
You can also save that id inside the comment object if you need to use it later. So this is how it looks like in code:
Map<String, Object> map = new HashMap<>();
map.put("noOfLikes", 0);
map.put("commentId", commentId);
rootRef
.child(UserId)
.child(PhotoId)
.child("comments")
.child(commentId)
.updateChildren(map);
Once you have this key
, you can use it in your reference to update the number of likes. This type of operation is usually done using Firebase transaction and for that I recommend see my answer from this post in which I have explained how to update a score property but same principle aplly in the case of likes.
The second approach would be to create an entire new top level collection like this:
Firebase-rot
|
--- comments
|
--- commentId
|
--- noOfLikes: 1
Using this solution it will be more easy for you to query the database becuase to get the number of likes you'll need only this simple reference:
DatabaseReference noOfLikesRef = rootRef
.child("comments")
.child(commentId)
.child("noOfLikes");
noOfLikesRef.addListenerForSingleValueEvent(/* ... */);

- 130,605
- 17
- 163
- 193
Try this:
Fetch the commentID before storing it like this:
String CommentId = myRef.push().getKey();
Save the ID along with comment data:
myRef.child(CommentId).set(yourValuesHashMap);
Now, when you retrieve the comments, you'll have the ID of each comment and you can use that the insert the likes.

- 3,438
- 2
- 17
- 33