How to get specific pushedID in Firebase?
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(/* ... */);