How to redirect multiple types of users to their respective Activities?
I am creating a voting app on Firebase. I have 3 types of users. So far i can successfully redirect 2 kinds of users (STUDENTS, TEACHERS) to their respective activities after they login all with the code below, MY Users so far But now i have to add another user (ADMIN) and like other users, admin too should be redirected to their own specific activity after login. I am confused as to how to modify my code for a third user.
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
if (mAuth.getCurrentUser() != null) {
String uid = mAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
uidRef = rootRef.child("STUDENTS").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//start students activity
startActivity(new Intent(MainActivity.this, student.class));
} else {
//start teachers activity
startActivity(new Intent(MainActivity.this, teacher.class));
}
}
//
@Override
public void onCancelled(DatabaseError databaseError)
{
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
}
else{
Log.d("TAG", "firebaseUser is null");
}
}
};
Solution 1:
Using onlye if (dataSnapshot.exists())
will not solve your 3 types of user problem. Assuming that the type of the third user is 3
, a change in your database structure is needed. So your new database schema should look like this:
Firebase-root
|
--- users
|
--- uidOne
| |
| --- name: "Ed"
| |
| --- type: 1
|
--- uidTwo
| |
| --- name: "Tyff"
| |
| --- type: 2
|
--- uidOne
|
--- name: "Admin"
|
--- type: 3
Now you shoud add a listener on the uid
node and check the type of the user like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child("Type").getValue(Long.class) == 1) {
startActivity(new Intent(MainActivity.this, student.class));
} else if (dataSnapshot.child("TYPE").getValue(Long.class) == 2) {
startActivity(new Intent(MainActivity.this, teacher.class));
} else if (dataSnapshot.child("TYPE").getValue(Long.class) == 3) {
startActivity(new Intent(MainActivity.this, admin.class));
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);