3

I have an application with two different types of users one as Teacher and the Second a normal user. if a normal member logs in, he will go to normal_memberActivity and if he's a Teacher member, he'll go to Teacher_memberActivity. How do I do this in loginActivity?

My Firebase structure:

1

this is database firebase rules

 { 
   "rules": {
  ".read": true,

  ".write":true}

}
AL.
  • 36,815
  • 10
  • 142
  • 281
Asmahan
  • 139
  • 1
  • 4
  • 10

4 Answers4

4

i have been solving this problem for a week. I'm sorry to say the solution proposed above is kinda misleading. Thus, i have a better solution for this, and its 101% workable !

First, this is my real-time database in Firebase: I created a child "type" for each type of users created. Then, i set seller's account as 1 and buyer's account as 2 inside the "type" child's value.

Second, after i successfully verified the login details. At that particular moment, i use the firebase real-time datasnapshot to pull the type value based on the current user's UID, then i verified whether is the value is equal to 1 or 2. Finally i able to start the activity based on the type of user.

Account Create code:

private void registerUser() {
    progressDialog = new ProgressDialog(this);
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();
    if (TextUtils.isEmpty(email)) {
        Toast.makeText(this, "Please Enter Emailsss", Toast.LENGTH_SHORT).show();
        return;
    }
    if (TextUtils.isEmpty(password)) {
        Toast.makeText(this, "Please Enter Your PASSWORDS", Toast.LENGTH_SHORT).show();
        return;
    }

    progressDialog.setMessage("Registering User Statement..");
    progressDialog.show();


    //Firebase authentication (account save)
    firebaseAuth.createUserWithEmailAndPassword(email, password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        //user already logged in
                        //start the activity
                        finish();
                        onAuthSuccess(task.getResult().getUser());
                       // startActivity(new Intent(getApplicationContext(), MainActivity.class));

                    } else {
                        Toast.makeText(signupActivity.this, "Could not registered , bullcraps", Toast.LENGTH_SHORT).show();

                    }
                    progressDialog.dismiss();

                }
            });
}
private void onAuthSuccess(FirebaseUser user) {
    //String username = usernameFromEmail(user.getEmail());


    // Write new user
    writeNewUser(user.getUid(), toggle_val, user.getEmail());

    // Go to MainActivity
    startActivity(new Intent(signupActivity.this, MainActivity.class));
    finish();
}

private void writeNewUser(String userId, int type, String email) {
    User user = new User(Integer.toString(type), email);
    if (type == 1){
        mDatabase.child("users").child(userId).setValue(user);
    }
    else {
        mDatabase.child("users").child(userId).setValue(user);
    }
    }
    if (toggleBut.isChecked()){
        toggle_val = 2;
        //Toast.makeText(signupActivity.this, "You're Buyer", Toast.LENGTH_SHORT).show();
    }
    else{
        toggle_val = 1;
        //Toast.makeText(signupActivity.this, "You're Seller", Toast.LENGTH_SHORT).show();
    }

Sign in Account code:

 private void userLogin () {
    String email = editTextEmail.getText().toString().trim();
    String password = editTextPassword.getText().toString().trim();

    if(TextUtils.isEmpty(email)){
        Toast.makeText(this, "Please Enter Emailsss", Toast.LENGTH_SHORT).show();
        return;
    }
    if(TextUtils.isEmpty(password)){
        Toast.makeText(this, "Please Enter Your PASSWORDS", Toast.LENGTH_SHORT).show();
        return;
    }

    progressDialog.setMessage("Login....");
    progressDialog.show();

    firebaseAuth.signInWithEmailAndPassword(email,password)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    progressDialog.dismiss();
                    if(task.isSuccessful()){
                        onAuthSuccess(task.getResult().getUser());
                        //Toast.makeText(signinActivity.this, "Successfully Signed In", Toast.LENGTH_SHORT).show();
                    }
                    else {
                        Toast.makeText(signinActivity.this, "Could not login, password or email wrong , bullcraps", Toast.LENGTH_SHORT).show();
                    }
                }
            });
}

private void onAuthSuccess(FirebaseUser user) {

    //String username = usernameFromEmail(user.getEmail())
    if (user != null) {
        //Toast.makeText(signinActivity.this, user.getUid(), Toast.LENGTH_SHORT).show();
        ref = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("type");
        ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String value = dataSnapshot.getValue(String.class);
                //for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                   // Toast.makeText(signinActivity.this, value, Toast.LENGTH_SHORT).show();
                    if(Integer.parseInt(value) == 1) {
                        //String jason = (String) snapshot.getValue();
                        //Toast.makeText(signinActivity.this, jason, Toast.LENGTH_SHORT).show();
                        startActivity(new Intent(signinActivity.this, MainActivity.class));
                        Toast.makeText(signinActivity.this, "You're Logged in as Seller", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        startActivity(new Intent(signinActivity.this, BuyerActivity.class));
                        Toast.makeText(signinActivity.this, "You're Logged in as Buyer", Toast.LENGTH_SHORT).show();
                        finish();
                    }
                }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }

    }
  • Thanks for the code.. I have a doubt in 1st section (Account Create code) in the function "writeNewUser" you have used the same line of code under if (type =1 ) condition and for else condition , [ mDatabase.child("users").child(userId).setValue(user);] ,is that is correct or any typo error..please clarify .. – Abhishek Mar 09 '21 at 15:37
1

I suggest you have this kind of structure in your database

users
---details...
---type

The type key would now contain whether your user is normal or a teacher. Now using FirebaseAuthentication which I think you already have integrated in your app, you could use:

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

to get the currently logged in user. With that, you can now use:

String uid = user.getUid();

in order to get the UID of the currently logged in user which I think you have used as the key for your users.

Now with the UID ready, you could use a Firebase query to get the type of that specific user and go to the specific Activity based on their type.

Query userQuery = FirebaseDatabase.getInstance().getReference()
                     .child("users").orderByKey().equalTo(uid);
userQuery.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String type = dataSnapshot.child("type").getValue().toString();
        if(type.equals("Teacher"){
            //Go to TeacherMemberActivity
        } else {
            //Go to NormalMemberActivity
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});
Kurt Acosta
  • 2,407
  • 2
  • 14
  • 29
1

You can verify what group a user belongs(teacher or user) by attaching an event listener inside the FirebaseAuth.AuthStateListener and redirecting the user to the appropriate activity as follows

private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference ref;

    mAuthListener = new FirebaseAuth.AuthStateListener() {
        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
            FirebaseUser user = firebaseAuth.getCurrentUser();
            if (user != null) {
                ref = FirebaseDatabase.getInstance().getReference().child("hire-teachers").child("teachers");

                ref.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                            if(FirebaseAuth.getInstance().getCurrentUser().getUid().equals(snapshot.getKey())){
                                startActivity(new Intent(SignInActivity.this, Teacher_memberActivity.class));
                            }
                        }
                        startActivity(new Intent(SignInActivity.this, Normal_memberActivity.class));
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            } else {
                // User is signed out
            }
            // ...
        }
    };  

In the above implementation of the Firebase API, I am checking to see if the user is a teacher. if true then start the Teacher_memberActivity if not, start the Normal_memberActivity.

T double
  • 349
  • 3
  • 12
  • Thanks for help, I have a problem with this code When I Logged as the Teacher didn't go to Teacher_memberActivity he jumped to Normal_memberActivity. Why? – Asmahan Apr 10 '17 at 09:52
  • ok, i think the problem should be with the database node we are pointing to. From the look of your database, i assumed the "hire-teacher" node is an immediate child of the root reference. please modify the line `ref = FirebaseDatabase.getInstance().getReference().child("hire-teachers").child("teachers"); ` so that it points to the node in the database exactly according to how that data in your database is. – T double Apr 10 '17 at 19:06
  • I asked the firebase support they told me it was possible because of "After the first startActivity, your application will immediately execute the next startActivity below the if clause. Try adding finish() and return statement after every startActivity call so that the calling activity will end once the application has executed startActivity." – Asmahan Apr 10 '17 at 20:54
  • Can you show me how do I add finish() and return ? I am a beginner – Asmahan Apr 10 '17 at 20:59
  • Well, to the best of my knowledge about the firebase sdk, return statements inside the `ondataChange()` method are invalid since the firebase server returns data to the app in a different thread from the activity thread. The `finish()` method is used to skip all execution inside the if else statement and move to the next block, Hence the second `startActivity()` method will still be called. That being said, I recommend that you replace all the code inside the `onDataChange()` method as i have done in my new answer below – T double Apr 10 '17 at 21:48
1

Here is the new code:

private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference ref;

mAuthListener = new FirebaseAuth.AuthStateListener() {
    @Override
    public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FirebaseUser user = firebaseAuth.getCurrentUser();
        if (user != null) {
            ref = FirebaseDatabase.getInstance().getReference().child("hire-teachers").child("teachers");

            ref.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    Boolean boolean = false;
                    for(DataSnapshot snapshot : dataSnapshot.getChildren()){
                        if(FirebaseAuth.getInstance().getCurrentUser().getUid().equals(snapshot.getKey())){
                           boolean = true;
                        }
                    }
                    if(boolean){
                        startActivity(new Intent(SignInActivity.this, Teacher_memberActivity.class));
                    }else{
                        startActivity(new Intent(SignInActivity.this, Normal_memberActivity.class));
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

        } else {
            // User is signed out
        }
        // ...
    }
};
T double
  • 349
  • 3
  • 12