How to redirect a user to a specific activity in Cloud Firestore?

前端 未结 2 1654

While Registering an account using Firebase auth I stored emails in 2 categories Teacher and Student. I add emails to Firestore 2 different categories Teacher and Student wi

2条回答
  •  感动是毒
    2020-12-19 11:57

    Using two different collections, one for each type of your users isn't quite a flexible solutions. Another more simpler solution might be:

    Firestore-root
       |
       --- users (collection)
            |
            --- uid (document)
            |    |
            |    --- email: "student@email.com"
            |    |
            |    --- password: "********"
            |    |
            |    --- type: "student"
            |
            --- uid (document)
                 |
                 --- email: "teacher@email.com"
                 |
                 --- password: "********"
                 |
                 --- type: "teacher"
    

    See, I have added the type of the user as a property of your user object. Now, to get a user based on the email address, please use the following lines of code:

    FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    CollectionReference usersRef = rootRef.collection("users");
    Query query = usersRef.whereEqualTo("email", "student@email.com")
    query.get().addOnCompleteListener(new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
            if (task.isSuccessful()) {
                for (QueryDocumentSnapshot document : task.getResult()) {
                    String email = document.getString("email");
                    String password = document.getString("password");
                    mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(/* ... */);
                }
            }
        }
    });
    

    Once the user is authenticated, to redirect the user to the corresponding activity, please use the following lines of code:

    String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
    usersRef.document(uid).get().addOnCompleteListener(new OnCompleteListener() {
        @Override
        public void onComplete(@NonNull Task task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    String type = document.getString("type");
                    if(type.equals("student")) {
                        startActivity(new Intent(MainActivity.this, Student.class));
                    } else if (type.equals("teacher")) {
                        startActivity(new Intent(MainActivity.this, Teacher.class));
                    }
                }
            }
        }
    });
    

提交回复
热议问题