如何在Firebase中获取特定的pushID? [英] How to get specific pushedID in Firebase?

查看:424
本文介绍了如何在Firebase中获取特定的pushID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Firebase作为后端制作类似Instagram的应用,而用户在任何照片中添加评论时,Firebase会生成新的ID,现在我想在用户单击赞"按钮时添加一个孩子(赞")这个随机生成的评论ID,但问题是如何获取特定的评论ID?

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?

推荐答案

有两种方法可以实现此目的.因此,如果您想访问特定的注释,则必须知道一些唯一标识该pcommentll的内容.第一种解决方案是在使用push()方法将新注释推入数据库时​​的确切时刻,将该随机ID存储在变量中.要获取该ID,您可以使用以下代码行:

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

如果以后需要使用该ID,也可以将该ID保存在注释对象中.这就是代码中的样子:

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

拥有此key后,就可以在参考中使用它来更新点赞的次数.通常使用 Firebase交易来完成此类操作为此,我建议从此

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

这篇关于如何在Firebase中获取特定的pushID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆