How to create user and upload data on Firebase in one single transaction

后端 未结 4 1719
情书的邮戳
情书的邮戳 2021-01-20 14:28

I am making a web application which creates a user on Firebase using email and password firebase.auth().createUserUsingEmailAndPassowrd()

After the account

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-20 14:38

    Because you're so afraid of worst case scenario (which is absolutely normal), here is one way to do it: Consider you have these fields: email, password, and address. The address field is the one you need to store in your database (with user uid, of course).

    First you try to register the user, and like Faizy said, you use onCompleteListener like this

    mAuth.createUserWithEmailAndPassword(email, password)
        .onCompleteListener(... {
            ... onComplete (... task) {
                if (task.isSuccessful()) {
                    doInsertTheData();
                }
    ...
    

    When task is successful, then you want to insert the data into database, which doInsertTheData() is created for

    private void doInsertTheData() {
         // I believe you familiar with Firebase database inserting method, so I skip the long part
         FirebaseDatabase...setValue(address, new CompletionListener() {
             ... onComplete(FirebaseError firebaseError, ...) {
                 if (firebaseError == null) {
                     // if your code reach here, its a happy ending
                 } else {
                     // if it reach here, then you can remove the signed in user
                     // and tell the user that their registration is failed and should try again
                     FirebaseAuth.getInstance().getCurrentUser().delete();
                 }
    

    And there you go, as long as the database saving process failed, the user credential will be deleted

    Note: I actually have another method in mind when I type this, but it's too complicated and I think this one is more easy to understand (I haven't try/use this though)

提交回复
热议问题