How to Redirect Multiple Types of Users to Their Respective Activities

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

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);

Direct to each activity according to type of user

Since in your database you have a node called users, then add a reference to that node, for example:

 FirebaseDatabase.getInstance().getReference("users").child(uid).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {

Then do the following:

Change this:

if(role=="patient"){

into this:

if(role.equals("patient")){

You need to use equals() when you want to compare the value of each object.

Trying to send Users to different Activities depending on type. keep getting Operator cannot be applied to database reference and String

You are getting the following error:

Operator == cannot be applied to Database reference and String

Because you are trying to compare two totally different types of objects:

ref.child("users").child("type") == "1"

The object on the left-hand side is an object of type DatabaseReference, while on the right-hand side is a String. These objects will never be equal. If you want to compare the value of the "type" property from the database with "1", then you should attach a listener and read that particular value, and right after that do the comparison, as explained in my answer from the following post:

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



Related Topics



Leave a reply



Submit