如何正确构造Java代码以将命名键下的值保存到Firebase Realtime数据库

时间:2019-01-29 10:19:09

标签: java android firebase firebase-realtime-database

我目前正在编写应用程序的一部分,用户在其中扫描包含用户UID值的QR码。进行扫描后,我想在Firebase Realtime数据库中创建一个新密钥,其中包含与具有该UID的用户相关的信息,即userInformation。以下是我希望将值存储为的格式的示例:

enter image description here

当前,它是在没有userInfromations键的情况下存储的,它仅与UID一起存储,如下所示: enter image description here

这是相关代码:

case FirebaseVisionBarcode.TYPE_TEXT:
            {
                final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
                userInformations = new ArrayList<>();
                DatabaseReference username = ref.child(item.getRawValue()).child("username");
                DatabaseReference dateOfBirth = ref.child(item.getRawValue()).child("dateOfBirth");

                username.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        String username = dataSnapshot.getValue(String.class);
                        //Toast.makeText(getApplicationContext(),username, Toast.LENGTH_LONG).show();

                        //it will create a unique id and we will use it as the Primary Key for our UserInfo
                        String id1 = ref.push().getKey();

                        //creating an UserInfo Object
                        UserInformation userInformation = new UserInformation(id1, username);

                        //Saving the Artist
                        ref.child(id1).setValue(userInformation);

                        //displaying a success toast
                        Toast.makeText(getApplicationContext(), username + " has been added", Toast.LENGTH_LONG).show();
                    }

我也意识到通过更改:

final DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

收件人:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference("userInformations");

我能够获得名为userInformations的密钥,但是它不再像下面那样保存userInformationName的值:

enter image description here

此刻,我只是不确定如何构造代码来同时获得这两个东西。

1 个答案:

答案 0 :(得分:1)

根据最后的彗星,获得如下所示的模式:

rootRef
  |
  --- userInformations
         |
         --- pushId
              |
              --- "userInformationId: "-LXO5 ... H-o3-P" 
              |
              --- "userInformationName: "spamemail0100@gmail.com"

请使用以下代码行:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userInformationsRef = rootRef.child("userInformations");
String userInformationId = userInformationsRef.push().getKey();
String userInformationName = "spamemail0100@gmail.com";
UserInformation userInformation = new UserInformation(userInformationId, userInformationName);
userInformationsRef.child(userInformationId).setValue(userInformation);