【问题标题】:How to retrieve unique random key as soon as it had been updated?如何在更新后立即检索唯一随机密钥?
【发布时间】:2019-02-03 23:02:36
【问题描述】:

我正在使用 Firebase。但我是firebase的新手。我的应用有一个上传帖子的活动,这里是 JSON 结构。

post:{
  uid1:{
        -random1:{
                  text:hello,
                  uploader:John
                 },
         -random2:{
                  text:hello2334,
                  uploader:John
                 },
      },
  uid2:{
        -random3:{
                  text:Mornig,
                  uploader:Jack
                  },
      }

  }
likes:{
  uid1:{
        -random1:{
                  uid4:true,
                  uid5:true
                 },
        -random2:{
                  uid4:true,
                  uid3:true,
                 }

... } 这是我的示例代码,当用户单击提交按钮以上传他的帖子时..

submit.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v){
                        post.push().setValue(textfield.getText());
                        /*I want to upload like node with the same random key but with different value. I don't know how to do it*/
                             }
                 });    

当用户点击帖子时,我用随机密钥更新帖子,然后我想用相同的随机密钥更新类似的东西。我不知道如何同时用相同的随机密钥上传到节点(只有 uid和随机 id 节点)因为我是菜鸟。我搜索了很多,但没有找到答案。 对不起,我的英语写作水平不好......

【问题讨论】:

标签: firebase firebase-realtime-database


【解决方案1】:

您可以在写入数据之前获取密钥。您是使用 push 方法,因此将创建密钥,以便在您需要使用 push 之前获取它,但也使用 setValue

ref = root.child("post").child(uid);
key = ref.push().key //it could be getKey() depending on the sdk
ref.child(key).setValue(yourObject);
root.child("likes").child(ownerUid).child(key).child(uid).setValue(true)

【讨论】:

  • 你的意思是我可以在更新之前得到随机密钥吗?我明天测试一下,因为太晚了,无法入睡。谢谢...
  • 我的意思是,是否有唯一的随机密钥来上传孩子?我一直认为更新后会在服务器上创建随机密钥。
  • 您可以在写入数据库之前获取自动生成的密钥,它只是伪随机,它使用客户端时间作为算法的一部分,您可以在此处查看完整说明firebase.googleblog.com/2015/02/…
  • 谢谢...它工作正常....:) 顺便说一下,让我知道最好的帖子和点赞数据库。我不认为我的数据库结构是好的。那你能给我一些建议吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
相关资源
最近更新 更多