1

Instead of using push() to generate id for child(user), can I use email of user as id in Firebase?

I tried this:

    private void userData(String emai1, String pass, String bal) {

    String id = emai1;
    int balance=Integer.valueOf(String.valueOf(bal));
    User user1 = new User(id,emai1,pass,balance);
    databaseReference.child(id).setValue(user1);

}

User class:

public class User {

 private String email;
 private int balance;
 private String password;
 private String id;

public User( String id,String email, String password , int balance) {
    this.email = email;
    this.balance = balance;
    this.password = password;
    this.id = id;
}



public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public int getBalance() {
    return balance;
}

public void setBalance(int balance) {
    this.balance = balance;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

}

Since I have used firebase auth, user gets registered but his info does not get added to firebase database.

Btw, before trying this, I was using push() to get the id and everything was working fine, but I want email as id instead generating a new id(since emails are unique anyway.)

RAGHHURAAMM
  • 1,099
  • 7
  • 15
echoaman
  • 71
  • 4
  • 15
  • See https://stackoverflow.com/questions/43863398/how-to-add-email-address-as-child-in-firebase, https://stackoverflow.com/questions/41713039/can-we-have-email-id-as-key-in-firebase-database?rq=1 – Frank van Puffelen Oct 14 '18 at 16:00

1 Answers1

1

You cannot use an email as unique key since it contains a dot . which is not allowed in the database.

Since you used firebase authentication then just use the user unique id instead of push()

 FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
 String userId=user.getUid();

This will give you the id, which you can then use in the database also.

DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("users").child(userId);
ref.child("name").setValue("name_here");
ref.child("email").setValue("email_here");

Then you would have:

users
  userId
    name: name_here
    email: email_here

Check this also:

Why use UID in Firebase? Should I use it

Peter Haddad
  • 78,874
  • 25
  • 140
  • 134