How to redirect a user to a specific activity in Cloud Firestore?

Saba Nayab :

While Registering an account using Firebase auth I stored emails in 2 categories Teacher and Student. I add emails to Firestore 2 different categories Teacher and Student with email and password. When I login I want to check that email belongs to which category (Teacher or Student) how can I do that I tried the firestore query isequalsto but it didn't differentiate.

Here is my database

Teacher

enter image description here

Student

enter image description here

Any other possible solution?

here is my code for login activity

package com.example.dell.step;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.CollectionReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.QuerySnapshot;

public class LoginActivity extends AppCompatActivity {


    private Button mRegbtn;
    private Button mloginbtn;
    private EditText mEmail;
    private EditText mPassword;

    private Toolbar mToolbar;

    private FirebaseAuth mAuth;

    private ProgressDialog mLoginDialog;
    private FirebaseFirestore firebaseFirestore;
    private CollectionReference collectionReference_I;
    private CollectionReference collectionReference_S;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);


        mAuth = FirebaseAuth.getInstance();

        //Progress Dialog

        mLoginDialog = new ProgressDialog(this);

        //FOr Toolbar

        mToolbar = findViewById(R.id.login_toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle("Login Account");


        mloginbtn = findViewById(R.id.login_btn);
        mEmail = findViewById(R.id.login_email);
        mPassword = findViewById(R.id.login_password);

        mRegbtn = findViewById(R.id.login_reg_btn);

        firebaseFirestore = FirebaseFirestore.getInstance();

        mRegbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent regIntent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(regIntent);
                finish();

            }
        });


        mloginbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = mEmail.getText().toString();
                String password = mPassword.getText().toString();

                if (!TextUtils.isEmpty(email) && !TextUtils.isEmpty(password)) {
                    mLoginDialog.setTitle("Login User");
                    mLoginDialog.setMessage("Please wait while we login to your account :)");
                    //it stops cancel Dialog when user touch on screen
                    mLoginDialog.setCanceledOnTouchOutside(false);
                    mLoginDialog.show();

                    login_user(email, password);
                }
            }
        });


    }

    private void login_user(final String email, final String password) {

        collectionReference_I = firebaseFirestore.collection("Teacher");
        collectionReference_S = firebaseFirestore.collection("Student");

        collectionReference_I.whereEqualTo("teacher_email", email).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot documentSnapshots) {

                mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {


                        if (task.isSuccessful()) {

                            //Dismiss the progress Dialog
                            mLoginDialog.dismiss();


                            //user is registered
                            Toast.makeText(LoginActivity.this, "Welcome to Teacher Account", Toast.LENGTH_SHORT).show();
                            Intent mainIntent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(mainIntent);
                            finish();


                        } else {

                            mLoginDialog.hide();

                            //if user is not registered
                            Toast.makeText(LoginActivity.this, "Cannot Log in Please check the form and try again!", Toast.LENGTH_LONG).show();

                        }

                    }
                });


            }
        });

        collectionReference_S.whereEqualTo("Student_email", email).get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot documentSnapshots) {

                mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {


                        if (task.isSuccessful()) {

                            //Dismiss the progress Dialog
                            mLoginDialog.dismiss();


                            //user is registered
                            Toast.makeText(LoginActivity.this, "Welcome to Student Account", Toast.LENGTH_SHORT).show();
                            Intent mainIntent = new Intent(LoginActivity.this, StudentMain.class);
                            startActivity(mainIntent);
                            finish();


                        } else {

                            mLoginDialog.hide();

                            //if user is not registered
                            Toast.makeText(LoginActivity.this, "Cannot Log in Please check the form and try again!", Toast.LENGTH_LONG).show();

                        }

                    }
                });


            }
        });


    }
}
Alex Mamo :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=105158&siteId=1
Recommended