How to redirect multiple types of users to their respective Activities?

前端 未结 2 644
萌比男神i
萌比男神i 2020-11-22 11:43

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 afte

相关标签:
2条回答
  • 2020-11-22 12:18

    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);
    
    0 讨论(0)
  • 2020-11-22 12:25

    you need another data-structure, with users and roles/admin, roles/teacher, roles/student and then check which node has the key (also compatible with security rules).

    as you have it, you could simply remove the else branch and query all three nodes.

    0 讨论(0)
提交回复
热议问题