首页 > 解决方案 > 更新后如何检索唯一的随机密钥?

问题描述

我正在使用火力基地。但我是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节点)因为我是菜鸟。我搜索了很多,但没有找到答案。对不起,我的英语写作水平不好......

标签: firebasefirebase-realtime-database

解决方案


您可以在写入数据之前获取密钥。您使用的是 usibg 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)

推荐阅读