为什么我无法将数组的第一个和最后一个记录记录到Firestore

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么我无法将数组的第一个和最后一个记录记录到Firestore相关的知识,希望对你有一定的参考价值。

我正在尝试注册20个用户,并在Firebase Firestore上为每个用户创建一个文档。我的程序成功注册了20个用户,但在为他们创建文档时失败了。每次创建18个,19个文档,但它几乎总是跳过为第一个成员和我的数组的最后一个成员创建一个文档。 StudentCreator只是一个包含父数组的文件,学生数组包含20个项目。这是来自studentCreator.java的数组

public static String parent_names[]={ "Ahmet Lola", "Hüseyin Kutlutürk", "Ümit Uğrak", "Veysel Karani", "Serkan Gotar", "Dündar Zalim", "Kadir Berkay", "Uğur Özdemir", "Bünyamin Akgün", "Kaptan Price", "Selim Tekiner", "Gökçe Yılan", "Talip Özkan", "Abdurrahman Tarikçi", "Selim Kirlier", "Hasan Can Doğan", "Erdem Gökşen", "Fatoş Ünal", "Nurgül Birtek", "Yuan Hui"};

这里的主要代码:

    public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private FirebaseAuth mAuth;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final Intent LoginActivity = new Intent(this,LoginActivity.class);
    final Intent TeacherActivity = new Intent(this,TeacherActivity.class);
    final Intent ParentActivity = new Intent(this,ParentActivity.class);
    final Intent ManagerActivity = new Intent(this,ManagerActivity.class);


    for (int i = 0; i < 20; i++)
    {
        mAuth = FirebaseAuth.getInstance();
        final String username = StudentCreator.parent_names[i].replaceAll(" ", "") + StudentCreator.student_numbers[i];
        final String email = username + "@onurmail.com";
        final String password = "123456";

        final String student_name = StudentCreator.student_names[i];
        final String parent_name = StudentCreator.parent_names[i];
        //Registration is successul here.
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d("User Registered", "createUserWithEmail:success");

                            final FirebaseUser user = mAuth.getCurrentUser();
                            final String user_id = user.getUid();
                            //I get valid userId's for 20 users.
                            //CREATE STUDENT OBJECT AND FIREBASE INSTANCES
                            final FirebaseFirestore db = FirebaseFirestore.getInstance();

                            final Map<String, Object> student = new HashMap<>();
                            student.put("student_name", student_name);
                            student.put("parent_name", parent_name);
                            //My first element of array comes here and prints its parent name and student name perfectly but cant see anything about it on database.
                            //PUT STUDENT TO THE DB
                            db.collection("TED_Ankara")
                                    .document(parent_name)
                                    .set(student)
                                    .addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            if (task.isSuccessful()) {
                                                Toast.makeText(getApplicationContext(), "User  inserted sucessfully: "+parent_name,
                                                        Toast.LENGTH_SHORT).show();

                                            }
                                            else {
                                                Toast.makeText(getApplicationContext(), "User cannot be inserted: "+parent_name,
                                                        Toast.LENGTH_SHORT).show();
                                            }

                                        }
                                    });

                            //PUT STUDENT TO THE DB



                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "createUserWithEmail:failure", task.getException());
                            Toast.makeText(getApplicationContext(), "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }

                });

    }
  }
}

请帮忙。我对addOnCompleteListener和firebaseAuth的用法持怀疑态度。但我不确定。谢谢你的帮助。

编辑:添加没有for循环的第一个成员没有任何问题。所以我猜问题是关于for循环。

答案

Firebase SDK只能有一个活动用户。由于你是在一个所谓的紧密循环中运行数组,我怀疑你可能在代码开始为前一个用户编写文档之前创建了一个下一个用户。要验证这是否确实是问题,您可以尝试查看是否可以解决此问题吗?

添加功能以创建用户

void createNextUser(List<String> student_names, List<String> student_numbers, List<String> parent_names) {
  if (student_names.size() > 0 && student_numbers.size() > 0 && parent_names.size() > 0) {
    final String student_name = student_names.remove(0);
    final String student_number = student_numbers.remove(0);
    final String parent_name = parent_names.remove(0);
    final String username = parent_name.replaceAll(" ", "") + student_number;
    final String email = username + "@onurmail.com";
    final String password = "123456";


    mAuth.createUserWithEmailAndPassword(email, password)
        .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    // Sign in success, update UI with the signed-in user's information
                    Log.d("User Registered", "createUserWithEmail:success");

                    final FirebaseUser user = mAuth.getCurrentUser();
                    final String user_id = user.getUid();
                    //I get valid userId's for 20 users.
                    //CREATE STUDENT OBJECT AND FIREBASE INSTANCES
                    final FirebaseFirestore db = FirebaseFirestore.getInstance();

                    final Map<String, Object> student = new HashMap<>();
                    student.put("student_name", student_name);
                    student.put("parent_name", parent_name);
                    //My first element of array comes here and prints its parent name and student name perfectly but cant see anything about it on database.
                    //PUT STUDENT TO THE DB
                    db.collection("TED_Ankara")
                            .document(parent_name)
                            .set(student)
                            .addOnCompleteListener(new OnCompleteListener<Void>() {
                                @Override
                                public void onComplete(@NonNull Task<Void> task) {
                                    if (task.isSuccessful()) {
                                        Toast.makeText(getApplicationContext(), "User  inserted sucessfully: "+parent_name,
                                                Toast.LENGTH_SHORT).show();

                                    }
                                    else {
                                        Toast.makeText(getApplicationContext(), "User cannot be inserted: "+parent_name,
                                                Toast.LENGTH_SHORT).show();
                                    }

                                    // Now that we're done with this user, move on to the next one
                                    createNextUser(student_names, student_number, parent_names);
                                }
                            });

                } else {
                    // If sign in fails, display a message to the user.
                    Log.w(TAG, "createUserWithEmail:failure", task.getException());
                    Toast.makeText(getApplicationContext(), "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                }

            }

        });    
  }
}

这段代码的最大区别在于它只在创建了上一个用户及其文档后才开始创建下一个用户。它通过以下方式实现:

  1. 它在启动时从列表中删除当前学生 final String student_name = student_names.remove(0); final String student_number = student_numbers.remove(0); final String parent_name = parent_names.remove(0);
  2. 在写完文件后自称 // Now that we're done with this user, move on to the next one createNextUser(student_names, student_number, parent_names);

现在剩下要做的就是用你的onCreate开始这个过程:

createNextUser(Arrays.asList(StudentCreator.student_names), Arrays.asList(StudentCreator.student_numbers), Arrays.asList(StudentCreator.parent_names));

注意:为其他用户创建帐户是一项管理操作,因此通常不应从android客户端执行。我强烈建议您查看Firebase Admin SDK,它可以更好地支持此类操作。它必须在受信任的环境中使用,因此不能在Android应用程序中使用,例如您的开发计算机,您控制的服务器或云功能。

以上是关于为什么我无法将数组的第一个和最后一个记录记录到Firestore的主要内容,如果未能解决你的问题,请参考以下文章

我无法将记录添加到数据库

Informix:如何获取最后插入记录的 id

laravel 无法将记录保存到数据库

将项目添加到数组(状态)并且它正在更新状态中的先前记录

将 SQL 查询返回的记录拆分为数组

将数据库记录存储到数组中