How to store data in realtime database in firebase during user registration?

21,655

Solution 1

From the createUserWithEmailAndPassword method reference

Tries to create a new user account with the given email address and password. If successful, it also signs the user in into the app.

That means you don't need to authenticate the user again after the signup process completed.

To make sure that the task is complete and the firebaseUser is not null, better add AuthStateListener to your FirebaseAuth instead of saving data inside onComplete method, the code is in the official guide

Then you can save the data if the user is authenticated.

public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
    FirebaseUser user = firebaseAuth.getCurrentUser();
    if (user != null) {
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
        Map<String, String> map = new HashMap<>();
        map.put("provider", user.getProviders().get(0));
        if(user.getProviderData().containsKey("displayName")) {
            map.put("displayName", user.getProviderData().get("displayName").toString());
        }
        ref.child("users").child(user.getUid()).setValue(map);
    } 
}

Solution 2

Suppose if you want to add the user name on database then write

String name = etName.getText().toString().trim();

then Simply create object of DatabaseReference class eg:

 DatabaseReference myRootRef = FirebaseDatabase.getInstance().getReference();

 DatabaseReference userNameRef =  myRootRef.child("User Name");

 userNameRef.setValue(name);

// to add email
String email = etEmail.getText().toString().trim();
DatabaseReference userEmail = myRootRef.child("Email ");
userEmail.setValue(email);

In the same way you can do it for rest of the things

This will store the data as JSON tree where the root is myRootRef and its child will be userNameRef

Solution 3

For anyone else having a similar problem, a common cause of data not being persisted in Firebase is the child name in Realtime Database|Rules not matching the name in your java code:

enter image description here

Java code:

enter image description here

Again, you should be calling:

ref.child("users").child(firebaseUser.getUid()).setValue(<YOUR_POJO_OBJECT>);

instead of

 ref.child("users").child(authData.getUid()).setValue(map);
Share:
21,655
Gian7
Author by

Gian7

Updated on February 15, 2020

Comments

  • Gian7
    Gian7 about 4 years

    I'm making socialmedia-like app that has user profile. I want to save their profile data upon their registration using their uid. Although the registration is successful, profile is not saving in the firebase database. I've also checked the rules, and read and write is set for authenticated users.

    Here's my code:

    public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    
    private Button btn_reg;
    private EditText etName, etEmail, etPassword, etCPassword, etMobile, etSchoolCompany, etLocation;
    private ProgressDialog progressDialog;
    private FirebaseAuth firebaseAuth;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
    
        Firebase.setAndroidContext(this);
    
        firebaseAuth = FirebaseAuth.getInstance();
    
        progressDialog = new ProgressDialog(this);
    
        btn_reg = (Button)findViewById(R.id.btnRegister);
        etName = (EditText)findViewById(R.id.etName);
        etEmail = (EditText)findViewById(R.id.etEmail);
        etPassword = (EditText)findViewById(R.id.etPassword);
        etCPassword = (EditText)findViewById(R.id.etCPassword);
        etMobile = (EditText)findViewById(R.id.etMobile);
        etSchoolCompany = (EditText)findViewById(R.id.etSchoolCompany);
        etLocation = (EditText)findViewById(R.id.etLocation);
    
        btn_reg.setOnClickListener(this);
    }
    
    @Override
    public void onClick (View view){
        if(view == btn_reg){
            registerUser();
        }
    }
    
    private void registerUser(){
        String name = etName.getText().toString();
        String mobile = etMobile.getText().toString();
        String SchoolCompany = etSchoolCompany.getText().toString();
        String location = etLocation.getText().toString();
        final String email = etEmail.getText().toString().trim();
        final String password = etPassword.getText().toString().trim();
        String cpassword = etCPassword.getText().toString().trim();
    
        progressDialog.setMessage("Registering..");
        progressDialog.show();
    
        //REGISTERING USER
        firebaseAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if(task.isSuccessful()){
    
                            //THIS IS FOR STORING AUTHENTICATED USER'S DATA
                            final Firebase ref = new Firebase("https://myfirebase.firebaseio.com");
                            ref.authWithPassword(email, password, new Firebase.AuthResultHandler(){
                                @Override
                                public void onAuthenticated(AuthData authData){
                                    // Authentication just completed successfully :)
                                    Map<String, String> map = new HashMap<String, String>();
                                    map.put("provider", authData.getProvider());
                                    if(authData.getProviderData().containsKey("displayName")) {
                                        map.put("displayName", authData.getProviderData().get("displayName").toString());
                                    }
                                    ref.child("users").child(authData.getUid()).setValue(map);
                                }
                                @Override
                                public void onAuthenticationError(FirebaseError error) {
                    //ERRORS TODO
                                }
                            });
                            progressDialog.hide();
                            Toast.makeText(RegisterActivity.this, "Registered Successfully", Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(RegisterActivity.this, "Registration failed, please try again", Toast.LENGTH_SHORT).show();
                        }
                    }
    
                });
    }
    
    
    }
    
  • Ethan
    Ethan almost 8 years
    How can I check if the proposed email has already been registered?
  • Gian7
    Gian7 almost 8 years
    @Ethan I think you need to authenticate it, see my code above.. below the line //THIS IS FOR STORING AUTHENTICATED USER'S DATA.. I think that's how you check if your email is already registered. Or if you're error handling if the email is already registered, kindly check Full Error Listing
  • Gian7
    Gian7 almost 8 years
    I tried it private void reguser(){ String email = etEmail.getText().toString().trim(); myRootRef = FirebaseDatabase.getInstance().getReference(); DatabaseReference RootUsers = myRootRef.child("users"); RootUsers.setValue(email); } but I'm getting error ` java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/firebase/database/FirebaseDatabase;` on line of myRootRef
  • Amit Upadhyay
    Amit Upadhyay almost 8 years
    @Gian7 are you sure if firebase database is properly synchronized in your project?
  • Gian7
    Gian7 almost 8 years
    @AmitUpadhyay Yes, I believe it is so.. I've compared my version to several tutorials and guides provided in firebase documentation. Do you want me to double check onto something (dependencies, etc.) to make sure? By the way, here's my Firebase database structure.
  • Gian7
    Gian7 almost 8 years
    Sorry for late response.. I found your answer helpful however, I didn't used map, instead I used POJO as I've read from other guides that's what experts recommend. :)
  • Wilik
    Wilik almost 8 years
    yeah agree, POJO is better. It's just easier to give example in Map. Cheers :)
  • Erum
    Erum over 7 years
    i m getting inside block task.isSuccessfull ----> false but still its calling onAuthStateChanged method as well
  • Muhammad Younas
    Muhammad Younas about 7 years
    your solution not help me it is missing some keys and values and i am not able to solve