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?

Solution 1

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

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

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:

   --- 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
noOfLikesRef.addListenerForSingleValueEvent(/* ... */);

Solution 2

Try this:

  1. Fetch the commentID before storing it like this:

    String CommentId = myRef.push().getKey();

  2. Save the ID along with comment data:


  3. Now, when you retrieve the comments, you'll have the ID of each comment and you can use that the insert the likes.