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:
this is database firebase rules
{
"rules": {
".read": true,
".write":true}
}
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) {
}
});
}
}
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) {
}
});
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.
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
}
// ...
}
};
Related
This is the JSON text
{
"User" : {
"E10W6iRbAUOa5XbFnedUuepswsw2" : {
"email" : "jay#gmail,com",
"type" : "Admin"
},
"Od6G6kbPHrScLVYrqmovaFP0gw03" : {
"email" : "gloria#yahoo,com",
"type" : "User"
},
"jCiHZCIThdQi1LhVSonN6UNxRok2" : {
"email" : "clara#yahoo,com",
"type" : "User"
}
}
}
on if (login.getType().equals("Admin") && login.getType() != null)
or if there are any other errors please let me know
public class SignInActivity extends AppCompatActivity {
private EditText memail;
private EditText mpassword;
private Button mlogin;
private Button mregister;
private ProgressBar mpgbar;
private FirebaseAuth mAuth;
FirebaseDatabase database;
DatabaseReference users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
database = FirebaseDatabase.getInstance();
users = database.getReference("User");
mAuth = FirebaseAuth.getInstance();
memail = findViewById(R.id.emailtv);
mpassword = findViewById(R.id.passwordtv);
mlogin = findViewById(R.id.loginBtn);
mregister = findViewById(R.id.regBtn);
mpgbar = findViewById(R.id.progressBar);
mregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SignInActivity.this, RegisterActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return;
}
});
mlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
LoginUser(memail.getText().toString(), mpassword.getText().toString());
}
});
}
private void inProgress(boolean x) {
if (x) {
mpgbar.setVisibility(View.VISIBLE);
mlogin.setEnabled(false);
mregister.setEnabled(false);
} else {
mpgbar.setVisibility(View.GONE);
mlogin.setEnabled(true);
mregister.setEnabled(true);
}
}
private boolean isEmpty() {
if (TextUtils.isEmpty(memail.getText().toString())) {
memail.setError("REQUIRED");
return true;
}
if (TextUtils.isEmpty(mpassword.getText().toString())) {
mpassword.setError("REQUIRED");
return true;
}
return false;
}
private void LoginUser(final String email, final String pwd) {
if (isEmpty()) return;
inProgress(true);
users.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!email.isEmpty()) {
User login = dataSnapshot.child(email).getValue(User.class);
if (login.getType().equals("Admin") && login.getType() != null) {
mAuth.signInWithEmailAndPassword(email.replace(",","."), pwd)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(SignInActivity.this, "User signed in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignInActivity.this, AdminPage.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignInActivity.this, "Sign in failed" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
} else if (login.getType().equals("User") && login.getType() != null) {
if (isEmpty()) return;
inProgress(true);
mAuth.signInWithEmailAndPassword(email.replace(",","."), pwd)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(SignInActivity.this, "User signed in", Toast.LENGTH_LONG).show();
Intent intent = new Intent(SignInActivity.this, Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SignInActivity.this, "Sign in failed" + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
else
{
Toast.makeText(SignInActivity.this, "Sign in failed" , Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
It supposed to redirect user to home and admin to admin page. But it always crash.
You're loading the entire /User node, and then try to read a single User.class from it. That won't work, as /User contains multiple users. But you'll also first want to query the children under /User to only read users with the email address you're looking for.
Something like this:
private void LoginUser(final String email, final String pwd) {
Query query = users.orderByChild("email").equalTo(email)
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
User login = userSnapshot.getValue(User.class);
...
}
}
}
});
}
The main differences:
Instead of loading all users, this queries the children under /User for the one(s) matching the email address.
Inside onDataChange there may be multiple matching child nodes, so we loop over those results.
Removed the child("email") inside the onDataChange, since that doesn't work if you're trying to read an entire User object.
I am making an android application using Firebase database and I want to check that the user is not in registered as an "Association" so I am checking if he belongs to the child "Association".
The method userLogin is supposed to not log in the user if he is under the child "Associations" and log in him otherwise.
However, it is not working and the user is logged in even if he is under "Associations"
private void userLogin() {
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
mAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
String RegisteredUserID = currentUser.getUid();
DatabaseReference jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Associations").child(RegisteredUserID);
jLoginDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(), "You are not registered", Toast.LENGTH_SHORT).show();
}
else
{
finish();
Intent intent = new Intent(SignInDonor.this, homedonor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}});}
else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
I did not tried this, but it should work, first, after you log in with a user and enters inside task.isSuccessful , you can retrieve the current logged in user with task.getResult().getUser().getUid(). Then just loop inside Associations and get each user key (I assume that Associations has userIDs inside as nodes with a certain value), then compare if the current logged in user is equal to one inside that node, if matchs it will pop up your Toast, if not you will be redirected.
Try this
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
DatabaseReference jLoginDatabase = FirebaseDatabase.getInstance().getReference().child("Associations");
jLoginDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
if(snapshot.getKey().equals(task.getResult().getUser().getUid()) {
Toast.makeText(getApplicationContext(), "You are not registered", Toast.LENGTH_SHORT).show();
}
else
{
finish();
Intent intent = new Intent(SignInDonor.this, homedonor.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
I used addListenerForSingleValueEvent because we only need to loop once at the reference and not keep listening for data
I'm trying to make a user authentication with Firebase and at the same time store the user Full name and email address in the database linked with the User UID that is created during authentication. Here, my database table name is Users and I have been trying the following code to link my user information with its UID.
With the following code, the user gets registered but no associated database is being formed. What am I doing wrong here? Thanks in advance for the suggestion.
public class SignUpActivity extends AppCompatActivity implements View.OnClickListener {
EditText editTextFullName, editTextEmail, editTextPassword;
private FirebaseAuth mAuth;
FirebaseDatabase database;
DatabaseReference ref;
Users users;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up);
editTextFullName = (EditText) findViewById(R.id.editTextFullName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
database = FirebaseDatabase.getInstance();
ref = database.getReference("Users");
users = new Users();
mAuth = FirebaseAuth.getInstance();
findViewById(R.id.buttonSignUp).setOnClickListener(this);
}
private void getValues() {
users.setFullName(editTextFullName.getText().toString());
users.setEmail(editTextEmail.getText().toString());
}
private void registerUser() {
final String fullname = editTextFullName.getText().toString().trim();
String email = editTextEmail.getText().toString().trim();
String password = editTextPassword.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(email, password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
progressBar.setVisibility(View.GONE);
if (task.isSuccessful()) {
finish();
startActivity(new Intent(SignUpActivity.this, ProfileActivity.class));
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
getValues();
ref.child(""+ user +"").setValue(users);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
if (task.getException() instanceof FirebaseAuthUserCollisionException) {
Toast.makeText(getApplicationContext(), "You are already registered", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonSignUp:
registerUser();
break;
}
}
}
Something like this:
Do not forget the executor class,this is a proper example:
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(SignupActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(SignupActivity.this, "createUserWithEmail:onComplete:" + task.isSuccessful(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "Authentication failed." + task.getException(),
Toast.LENGTH_SHORT).show();
} else {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
finish();
}
}
});
}
});
}
you are finishing the activity before it can write to database when you call
finish();
method
fire the intent once the data has been written to database i.e after
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
getValues();
ref.child(""+ user +"").setValue(users);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
startActivity(new Intent(SignUpActivity.this, ProfileActivity.class));
finish();
like this
You don't need value event listener for that you can directly add to database like this :
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
databaseReference.push().setValue(users);
and you have to call finish(); after the database call
Start Activity and call finish() after setting the value to Database as #Rohit has suggested.
One more suggestion is; if you want to save data using UID, you will have to set it in the reference path like below:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user != null) {
String UID = user.getUid(); //get UID of currently logged in user(new user in your case)
ref.child(UID).setValue(users); //this will give you expected structure
startActivity(new Intent(SignUpActivity.this, ProfileActivity.class));
finish();
}
I am using Firebase Authentication in my app where the users can register using Email & Password and he has to verify the email.
The user gets the verification mails, but when he verifies it and comes back to the app, the isEmailVerified() is always false. So my app still doesn't allow the user to use all functions in spite of the fact that he has verified his email.
But if they log out and login again, the isEmailVerified() returns true immediately. But is it not good to log out the user and login back again.
public class Profile extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference myRef;
TextView name;
Button logout;
FirebaseAuth auth;
String userStatus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
auth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
myRef = database.getReference("name");
name=findViewById(R.id.id_name);
logout=findViewById(R.id.id_logout);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
auth.signOut();
startActivity(new Intent(Profile.this, Login.class));
}
});
userStatus= String.valueOf(auth.getCurrentUser().isEmailVerified());
if (userStatus =="true")
{
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
name.setText("Hello my name is: "+value);
Log.d("ashu", "Value is: " + value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.d("ashu", "Failed to read value.", error.toException());
}
});
}
else {
Toast.makeText(Profile.this,"Verify your email ", Toast.LENGTH_SHORT).show();
name.setText("Verify your email");
}}}
Here is my answer after putting some logic
userStatus = String.valueOf(auth.getCurrentUser().isEmailVerified());
// user has not verified the email
Toast.makeText(Profile.this,"Verify your email ", Toast.LENGTH_SHORT).show();
name.setText("Verify your email");
auth.getCurrentUser().reload().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (userStatus =="true")
{
//if they have verified the email
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// retrieving the value of current user
String value = dataSnapshot.getValue(String.class);
name.setText("Hello my name is: "+value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.d("ashu", "Failed to read value.", error.toException());
}
});
}
else {
name.setText("Verify your mail");
}
}
});
}
In my application, I have two users--Event Member and Client--they have separate user login and registration. If a client log in he will go to the the client activity; if an event member will log in he will go to the event member activity. How will I make sure that the email is a client or an event member?
Below image shows my firebase structure:
Here is my code:
SignupClient.java
signupClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String cemail = clie_email.getText().toString().trim();
final String cpassword = clie_password.getText().toString().trim();
String ccpassword = clie_cpassword.getText().toString().trim();
final String cfname = clie_firstname.getText().toString().trim();
final String clname = clie_lastname.getText().toString().trim();
final String cbday = clie_birthday.getText().toString().trim();
final String ccountry = clie_country.getSelectedItem().toString();
final String cmobile = clie_mobile.getText().toString().trim();
auth.createUserWithEmailAndPassword(cemail, cpassword)
.addOnCompleteListener(_5_SignupClient.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Toast.makeText(_5_SignupClient.this, "createUserWithEmail: onComplete" + task.isSuccessful(), Toast.LENGTH_LONG).show();
if (!task.isSuccessful()){
Toast.makeText(_5_SignupClient.this, "Authentication Failed" + task.getException(),
Toast.LENGTH_LONG).show();
}
else {
AccountInfo accountInfo = new AccountInfo(cfname, clname, cemail, cpassword, cbday, ccountry, cmobile);
mDatabaseReference.child("client").push().setValue(accountInfo);
startActivity(new Intent(_5_SignupClient.this, _7_ViewClient.class));
finish();
}
}
});
}
});
LoginClient.java
loginClient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String clie_unameemail = clie_emailuname.getText().toString();
final String clie_pass = clie_password.getText().toString();
if(TextUtils.isEmpty(clie_unameemail)){
Toast.makeText(getApplicationContext(), "Field cannot be empty", Toast.LENGTH_LONG).show();
return;
}
if(TextUtils.isEmpty(clie_pass)){
Toast.makeText(getApplicationContext(), "Field cannot be empty", Toast.LENGTH_LONG).show();
return;
}
auth.signInWithEmailAndPassword(clie_unameemail, clie_pass)
.addOnCompleteListener(_3_LoginClient.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
ref = FirebaseDatabase.getInstance().getReference().child("client");
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(_3_LoginClient.this, _7_ViewClient.class));
}
}
// startActivity(new Intent(_3_LoginClient.this, Normal_memberActivity.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
// User is signed out
}
// ...
}
};
if (!task.isSuccessful()) {
// there was an error
if (clie_pass.length() < 8) {
clie_password.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(_3_LoginClient.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(_3_LoginClient.this, "Successfully Registered", Toast.LENGTH_LONG).show();
Intent intent = new Intent(_3_LoginClient.this, _7_ViewClient.class);
startActivity(intent);
finish();
}
}
});
}
});
I hope you could help me. Thank you!
On your db there should be one more field like we say it USER_TYPE. While registering the user send its USER_TYPE. suppose if you are registering a user as a CLIENT then inser db value USER_TYPE="CLIENT" and if its as an Event member registration then inser db value USER_TYPE="EVENT" and now once you logged in check its USER_TYPE and redirect him based upon his USER_TYPE