简体   繁体   中英

Why Firebase database getUid doesn't work?

Initially, I wrote a code to store the value in Firebase realtime database.

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.

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. When it was changed to 'name' in lieu of Uid, the intent activity doesn't start. 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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