How to redirect a user to a specific activity in Cloud Firestore?
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: "[email protected]"
| |
| --- password: "********"
| |
| --- type: "student"
|
--- uid (document)
|
--- email: "[email protected]"
|
--- 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", "[email protected]")
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> 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<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> 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));
}
}
}
}
});