简体   繁体   English

为什么 Firebase 数据库 getUid 不起作用?

[英]Why Firebase database getUid doesn't work?

Initially, I wrote a code to store the value in Firebase realtime database.最初,我编写了一个代码来将值存储在 Firebase 实时数据库中。

mDbRef = mDatabase.getReference().child("Users");
mDbRef.child("name").setValue(rname);
mDbRef.child("email").setValue(remail);

The child value was stored under its Uid in 'Users' child.子值存储在“用户”子项中的 Uid 下。

Then I changed the code to然后我将代码更改为

String name = userName.getText().toString();
mDbRef = mDatabase.getReference().child("Users").child(name);
mDbRef.child("name").setValue(rname);
mDbRef.child("email").setValue(remail);

Now, the child value was stored under its name in 'Users' child.现在,子值存储在其名称下的“用户”子项中。

Now I have two issues,现在我有两个问题,

  1. If I add same name with different sub child values, it was not accepted.如果我添加具有不同子子值的相同名称,则不会被接受。 How to rectify it?如何纠正?
  2. I wrote the following code to check user before starting an activity.我编写了以下代码来在开始活动之前检查用户。
    public void checkUserExists () {
        final String user_id = Objects.requireNonNull(uAuth.getCurrentUser()).getUid();
        mDbRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if (dataSnapshot.hasChild(user_id)) {
                    startActivity(new Intent (LoginActivity.this, HomeActivity.class));
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {        
            }
        });
    }

The new Intent activity was working fine when the child was under Uid.当孩子在 Uid 下时,新的 Intent 活动运行良好。 When it was changed to 'name' in lieu of Uid, the intent activity doesn't start.当它更改为“名称”代替 Uid 时,意图活动不会启动。 But if I restart the app after closing it, it directly goes to Home activity.但是如果我在关闭它后重新启动应用程序,它会直接进入家庭活动。 What should be done to rectify the issue?应该怎么做才能纠正这个问题?

May I suggest something like that:我可以提出这样的建议吗:

String key = mDatabase.child("users").push().getKey();
// key is generated by Firebase and is unique
mDbRef = mDatabase.getReference().child("users").child(key);
mDbRef.child("name").setValue(rname);
mDbRef.child("email").setValue(remail);

And check the documentation并检查文档

happy to help!很高兴能帮助你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM