android - 等待在 Android 应用程序中的触发器中创建的文档

标签 android firebase google-cloud-firestore

我有一个使用 firebase 的安卓应用。当用户注册时,我在 firebase 上有一个触发器,它使用用户的默认数据在集合中创建一个文档。

这是在 firebase 上用作触发器的函数代码:

    exports.sendWelcomeEmail = functions.auth.user().onCreate((user) => 
    {  
        var userCoinsCol = db.collection('user_data');
        userCoinsCol.doc(user.uid).set({
            coins : 100, // some another information for user you could save it here.
            active: true,
            completedRewards: 0
        })
        .then(() => {
            console.log("done");
            return;
        })
        .catch((err) =>
        {
            console.log("Error creating data for just created user. => "+err);
            return;
        });
    });

这一切都完美无缺。问题是在注册后,我需要用户数据,有时当用户注册时似乎还没有准备好应用程序在下一个 Activity 中使用。

所以,我的问题是,Android 应用程序是否有任何方法可以等待触发器创建该文档,然后再移动到将使用该用户数据的下一个 Activity ?

如您所料,这只会在用户首次注册时发生。稍后如果用户想再次使用该应用程序,一切正常,因为用户数据是在用户注册后立即创建的。

编辑:经过一番尝试,我得到了这个解决方案,但它似乎不太高效,因为它可以接收很多文件。我只是添加它以供引用:

public void CreateAccount()
{

    if(!TextUtils.isEmpty(emailreg.getText()) && !TextUtils.isEmpty(passreg.getText()))
    {
        mAuth.createUserWithEmailAndPassword(emailreg.getText().toString(), passreg.getText().toString())
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>()
        {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task)
            {

                progressBar.setVisibility(View.INVISIBLE);

                if (task.isSuccessful())
                {
                    // Sign in success, update UI with the signed-in user's information
                    final FirebaseUser user = mAuth.getCurrentUser();

                    // ----> Start waiting for the user_data document to be created and go to the next activity
                    FirebaseFirestore db = FirebaseFirestore.getInstance();
                    final EventListener<QuerySnapshot> listener = new EventListener<QuerySnapshot>() {
                        @Override
                        public void onEvent(@javax.annotation.Nullable QuerySnapshot queryDocumentSnapshots, @javax.annotation.Nullable FirebaseFirestoreException e) {
                            List<DocumentSnapshot> documents = queryDocumentSnapshots.getDocuments();

                            boolean found = false;
                            for(DocumentSnapshot ds : documents)
                            {
                                if(ds.getId().equals(user.getUid()))
                                {
                                    Intent intent = new Intent(LoginActivity.this, MainActivity.class); // Call the AppIntro java class
                                    startActivity(intent);
                                }

                            }
                        }
                    };

                    db.collection("user_data").addSnapshotListener(listener);

                } else
                {
                    // If sign in fails, display a message to the user.

                    Toast.makeText(LoginActivity.this, getString(R.string.tryagain), Toast.LENGTH_SHORT).show();

                }

                // ...
            }
        });

    }else
    {
        Toast.makeText(LoginActivity.this, getString(R.string.tryagain), Toast.LENGTH_SHORT).show();
        progressBar.setVisibility(View.INVISIBLE);

    }


}

最佳答案

So, my question is, is there any way for the android app to wait for the trigger to create that document before going forward to the next activity that will create that user data?

当然可以,通过添加一个完整的监听器。这意味着只有当数据成功写入数据库时​​,您才能更进一步。当您使用 DocumentReference 的 set() 时方法,返回的对象类型为 Task , 所以你可以简单地使用 addOnCompleteListener() .

yourDocumentRef.set(yourObject).addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            //Do what you need to do
        }
    }
});

编辑:

如果通过 Coud Functions 将用户文档添加到 Cloud Firestore 数据库,您可以更改应用程序的逻辑并创建用户文档客户端以及 Security Rules这是强制性的,因此您的用户无法使用数据。或者你附加一个快照监听器来实时验证数据。创建文档后,继续逻辑。

关于android - 等待在 Android 应用程序中的触发器中创建的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56393725/

相关文章:

java - 如何更新 Firebase 数据库中的子节点数据?

dart - 将字符串从 firestore 保存到变量

ios - swift & Firestore : AppDelegate and ViewControllers

firebase - 如何查看 Firebase 通知发送报告?

javascript - 无法将 "custom blob"保存到 Firestore

android - 从 Activity 中的重叠布局中点击先前的布局

android - 以编程方式在android中执行Touch事件

java - 使用 Intent 向多个联系人发送消息

java - ResultReceiver.send 抛出 nullpointerexception

javascript - 存储来自不同 Intent 的多个参数