How to separate two users in the firebase in android - android

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

Related

login different users from different collections on android studio using firebase firestore auth

I have 2 kinds of users for my android app -User and Donor and they are from different collections.
the problem is when I try to use the email and password of a User for the Donor instead of making a Toast saying "cannot log in" the app just crashes. I tried using .addOnFailureListener here but it doesnt work
anyways here's my code.
public class log_in extends AppCompatActivity {
EditText lEmail, lPassword;
Button btnLogIn;
Spinner UserDonor;
FirebaseAuth lFirebaseAuth;
FirebaseFirestore lFirestoreFirebase;
String userID, donorID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activtiy_log_in);
lEmail = findViewById(R.id.etxtEmailLogIn);
lPassword = findViewById(R.id.etxtPasswordLogIn);
UserDonor = findViewById(R.id.spnUserDonor);
lFirebaseAuth = FirebaseAuth.getInstance();
lFirestoreFirebase = FirebaseFirestore.getInstance();
btnLogIn = findViewById(R.id.btnLogIn);
//button log-in
btnLogIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = lEmail.getText().toString().trim();
String Password = lPassword.getText().toString().trim();
String userDonor = UserDonor.getSelectedItem().toString().trim();
//if User is selected on spinner
if (userDonor.equals("User")){
// authenticate the user
lFirebaseAuth.signInWithEmailAndPassword(Email, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
userID = lFirebaseAuth.getCurrentUser().getUid();
DocumentReference userRef = lFirestoreFirebase.collection("users").document(userID);
userRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String usertype;
usertype = documentSnapshot.getString("userType");
if (usertype.equals("user")){
startActivity(new Intent(getApplicationContext(), main_user.class));
finish();
}
else {
Toast.makeText(log_in.this, "no user account is Registered", Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(log_in.this, "cannot login" + task.getException().getMessage() , Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
});
}
else {
Toast.makeText(log_in.this, "cannot login" + task.getException().getMessage() , Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
}
});
}
//if Donor is selected on spinner
else if (userDonor.equals("Donor")){
// authenticate the donor
lFirebaseAuth.signInWithEmailAndPassword(Email, Password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()){
donorID = lFirebaseAuth.getCurrentUser().getUid();
DocumentReference donorRef = lFirestoreFirebase.collection("donors").document(donorID);
donorRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
String usertype;
usertype = documentSnapshot.getString("userType");
if (usertype.equals("donor")){
startActivity(new Intent(getApplicationContext(), main_user.class));
Toast.makeText(log_in.this, "donor Logged in", Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(log_in.this, "no donor account is Registered", Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(log_in.this, "cannot login" + task.getException().getMessage() , Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
});
}
else {
Toast.makeText(log_in.this, "cannot log in" + task.getException().getMessage() , Toast.LENGTH_SHORT).show();
lFirebaseAuth.signOut();
}
}
});
}
}
});
}
}
or is there a better way for this to work?

How to redirect different users to different activities using android studio and a realtime firebase database

I am developing an app on android studio and need to redirect clients and personal trainers to two different activities based on their role. Personal Trainers need to be directed to PTNoticeboardActivity and clients to NoticeboardActivity. Any suggestion on how to do this, here is my login code:
public class MainActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
}
public void loginUser(View View){
String email = ((EditText) findViewById(R.id.editText_Log_email)).getText().toString();
String password = ((EditText) findViewById(R.id.editText_Log_password)).getText().toString();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter email", Toast.LENGTH_LONG).show();
return;
}
if (TextUtils.isEmpty(password)){
Toast.makeText(this, "Please Enter Password", Toast.LENGTH_LONG).show();
return;
}
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
// startActivity(new Intent(getApplicationContext(), NoticeBoardActivity.class));
// finish();
} else {
Toast.makeText(MainActivity.this, "Login Unsuccessful", Toast.LENGTH_LONG).show();
}
}
});
}
}
Here is my register activity code below:
public class RegisterActivity extends AppCompatActivity {
EditText txt_fullname, txt_email, txt_mobilenumber, txt_repassword,
txt_password;
Button btn_register;
RadioButton radioJobClient, radioJobPT;
DatabaseReference databaseReference;
FirebaseDatabase firebaseDatabase;
String job ="";
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
txt_fullname = (EditText) findViewById(R.id.editText_fullname);
txt_email = (EditText) findViewById(R.id.editText_UserEmail);
txt_password = (EditText) findViewById(R.id.editText_Password);
txt_repassword = (EditText) findViewById(R.id.editText_rePassword);
txt_mobilenumber = (EditText) findViewById(R.id.mobilenumber);
btn_register = (Button) findViewById(R.id.button_reg);
radioJobClient = (RadioButton) findViewById(R.id.radio_Client);
radioJobPT = (RadioButton) findViewById(R.id.radio_PersonalTrainer);
databaseReference = FirebaseDatabase.getInstance().getReference("User");
// new code
firebaseAuth = FirebaseAuth.getInstance();
btn_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String fullname = txt_fullname.getText().toString();
final String email = txt_email.getText().toString();
final String mobilenumber = txt_mobilenumber.getText().toString();
final String password = txt_password.getText().toString();
final String rePassword = txt_repassword.getText().toString();
if (radioJobClient.isChecked()){
job = "Client";
}
if (radioJobPT.isChecked()){
job = "PT";
}
if (TextUtils.isEmpty(email)){
Toast.makeText(RegisterActivity.this, "Please enter Email", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(fullname)){
Toast.makeText(RegisterActivity.this, "Please enter fullname", Toast.LENGTH_LONG).show();
}
if (TextUtils.isEmpty(password)){
Toast.makeText(RegisterActivity.this, "Please enter password", Toast.LENGTH_LONG).show();
}
firebaseAuth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(RegisterActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
User user = new User(
fullname,
email,
mobilenumber,
password,
job
);
FirebaseDatabase.getInstance().getReference("User")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(RegisterActivity.this, "Registration Complete", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
} else {
Toast.makeText(RegisterActivity.this, "Registration Unsuccessful", Toast.LENGTH_LONG).show();
}
// ...
}
});
}
});
}
public void goLogin (View view){
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}
}
Database structure:
This is the most efficient way to do it:
When your user has created an account, create a child node in the firebase database as role with value as per the user. [could be client or personal trainer]
Then when your activity starts, fetch the value from the database like this:
First of all add a LOGIN BUTTON toyour login activity. When user presses that then only the login thing will take place.
Here is your modified MainActivity.java:
public class MainActivity extends AppCompatActivity {
private FirebaseAuth firebaseAuth;
String userRole;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth = FirebaseAuth.getInstance();
btnLogin = findViewById(R.id.btn_login_resource);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = ((EditText) findViewById(R.id.editText_Log_email)).getText().toString();
String password = ((EditText) findViewById(R.id.editText_Log_password)).getText().toString();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter email", Toast.LENGTH_LONG).show();
return;
}
else if (TextUtils.isEmpty(password)){
Toast.makeText(this, "Please Enter Password", Toast.LENGTH_LONG).show();
return;
}
else{
firebaseAuth.signInWithEmailAndPassword(email, password).addOnCompleteListener(MainActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_LONG).show();
jobRef = FirebaseDatabase.getInstance().getReference().child("User").child(pAuth.getCurrentUser().getUid()).child("job");
jobRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
userRole = dataSnapshot.getValue().toString();
if(userRole.equals("Client")){
startActivity(new Intent(MainActivity.this, NoticeboardActivity.class);
}
else {
startActivity(new Intent(MainActivity.this, PTNoticeboardActivity.class);
}
}catch (Throwable e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), databaseError.toString(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(MainActivity.this, "Login Unsuccessful", Toast.LENGTH_LONG).show();
}
}
});
}
}
}
});
.
Now one thing to care about is that anyone can reverse-engineer this code and illegally can get access to the data. So make sure the data in each activity is hosted in Firebase and you have set the appropriate firebase rules. If you want me to elaborate please let me know in the comments down below.

The app kept closing once I try sign in mainly this line if (login.getType().equals("Admin") && login.getType() != null)

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.

Login Failed When Saving Data.(Sign-up)

I'm making an Android project, and for starters I have been figuring out how signing up works. By the way, I used Firebase for this. Here's my code:
package com....
import...
public class MainActivity extends AppCompatActivity {
//VIEW AND WIDGETS
Button createUser, moveToLoginBtn;
EditText userEmailEdit, userPasswordEdit;
//FIREBASE AUTH FIELDS
FirebaseAuth nAuth;
FirebaseAuth.AuthStateListener nAuthlistener;
DatabaseReference mDatabaseRef, mUserCheckData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ASSIGN ID
createUser = (Button) findViewById(R.id.createUserBtn);
moveToLoginBtn = (Button) findViewById(R.id.moveToLogin);
userEmailEdit = (EditText) findViewById(R.id.emailEditTextCreate);
userPasswordEdit = (EditText) findViewById(R.id.passEditTextCreate);
//ASSIGN INSTANCE
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
mUserCheckData = FirebaseDatabase.getInstance().getReference().child("Users");
nAuth = FirebaseAuth.getInstance();
nAuthlistener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
final String emailForVer = user.getEmail();
mUserCheckData.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
checkUserValidation(dataSnapshot, emailForVer);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
}
}
};
//ON CLICK LISTENER
createUser.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final String userEmailString, userPassString;
userEmailString = userEmailEdit.getText().toString().trim();
userPassString = userPasswordEdit.getText().toString().trim();
if (!TextUtils.isEmpty(userEmailString) && !TextUtils.isEmpty(userPassString))
{
nAuth.createUserWithEmailAndPassword(userEmailString,userPassString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
DatabaseReference mChildDatabase = mDatabaseRef.child("Users").push();
String key_user = mChildDatabase.getKey();
mChildDatabase.child("isVerified").setValue("unverified");
mChildDatabase.child("userKey").setValue(key_user);
mChildDatabase.child("emailUser").setValue(userEmailString);
mChildDatabase.child("passWordUser").setValue(userPassString);
Toast.makeText(MainActivity.this, "User Account Created!", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, Profile.class));
}
else
{
Toast.makeText(MainActivity.this, "User Account Creation Fail", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
}
});
}
}
});
//MOVE TO LOGIN
moveToLoginBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
});
}
private void checkUserValidation(DataSnapshot dataSnapshot, String emailForVer) {
Iterator iterator = dataSnapshot.getChildren().iterator();
while (iterator.hasNext())
{
DataSnapshot dataUser = (DataSnapshot) iterator.next();
if(String.valueOf(dataUser.child("emailUser").getValue()).equals(emailForVer) && dataUser.child("emailUser") != null)
{
if(String.valueOf(dataUser.child("isVerified").getValue()).equals("unverified") && dataUser.child("isVerified") != null)
{
Intent in = new Intent(MainActivity.this, Profile.class);
in.putExtra("USER_KEY" , String.valueOf(dataUser.child("userKey").getValue()));
startActivity(in);
//in.putExtra("NAME_KEY" , String.valueOf(dataUser.child("nameKey").getValue()));
}else
{
startActivity(new Intent(MainActivity.this, Welcome.class));
}
}
}
}
#Override
protected void onStart() {
super.onStart();
nAuth.addAuthStateListener(nAuthlistener);
}
#Override
protected void onStop() {
super.onStop();
nAuth.removeAuthStateListener(nAuthlistener);
}
}
I think I have implemented my methods correctly. But it toasts:
User Account Creation Failed
Is my
checkUseValidation() method wrong? Any kind of help is appreciated.
Also please pay attention to my:
public void onComplete
method, I have set it right I think. I don't know why the data isn't getting saved to the firebase database. Or why is the task unsuccesful as show in line:
if (task.isSuccessful())
Thank you very much.
First, you should change the toast, in your fail condition, to
Toast.makeText(MainActivity.this, task.getException().getMessage(), Toast.LENGTH_LONG).show();
So that you get what wrong in the task.
But before that did you enable Email/Password in the console????
See Sign up new users from url: https://firebase.google.com/docs/auth/android/start/?authuser=0
If task.isSuccessful() is false.You can add this to get error
Log.w(TAG, "createUserWithEmail:failure",task.getException());
Update you code as:
createUser.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
final String userEmailString, userPassString;
userEmailString = userEmailEdit.getText().toString().trim();
userPassString = userPasswordEdit.getText().toString().trim();
if (!TextUtils.isEmpty(userEmailString) && !TextUtils.isEmpty(userPassString))
{
nAuth.createUserWithEmailAndPassword(userEmailString,userPassString).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful())
{
DatabaseReference mChildDatabase = mDatabaseRef.child("Users").push();
String key_user = mChildDatabase.getKey();
mChildDatabase.child("isVerified").setValue("unverified");
mChildDatabase.child("userKey").setValue(key_user);
mChildDatabase.child("emailUser").setValue(userEmailString);
mChildDatabase.child("passWordUser").setValue(userPassString);
Toast.makeText(MainActivity.this, "User Account Created!", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, Profile.class));
}
else
{
Log.w("TAG", "createUserWithEmail:failure",task.getException());
Toast.makeText(MainActivity.this, "User Account Creation Fail", Toast.LENGTH_LONG).show();
startActivity(new Intent(MainActivity.this, MainActivity.class));
}
}
});
}
}
});
You should see warning in logcat:

User login can'd identify user position

User register as student or tutor during registration which saved in firebase database but when login cannot identify the user position which saved in the firebase database so what should I do? Please anyone can give suggestion or advice me how to do this.
The database is save the uid from email authentication as the node under the root then rest details is the children of the uid.
The code like this
private FirebaseAuth auth;
private EditText un, pw;
private String getun, getpw, uid;
private Button bl;
private FirebaseDatabase db;
private DatabaseReference ref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
auth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance();
ref = db.getReference();
uid = auth.getCurrentUser().getUid();
ref = db.getReference("users").child(uid);
un = (EditText) findViewById(R.id.Lun);
pw = (EditText) findViewById(R.id.Lpw);
bl = (Button) findViewById(R.id.Lbt);
final TextView rl = (TextView) findViewById(R.id.Lreg);
//login
bl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getun = un.getText().toString().trim();
getpw = pw.getText().toString().trim();
loginaction(getun, getpw);
}
});
//open register page
rl.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ri = new Intent(Login.this,Register.class);
Login.this.startActivity(ri);
}
});
}
private void loginaction(String a, String b){
auth.signInWithEmailAndPassword(a, b).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
Log.d("Login", "Login Success" + task.isSuccessful());
if (!task.isSuccessful()) {
Log.w("Login", "Login Failed", task.getException());
Toast.makeText(Login.this, "Login Failed. Please try again", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(Login.this, "Login Success", Toast.LENGTH_SHORT).show();
ref.orderByChild("position").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String ps = dataSnapshot.getValue().toString();
if(ps.equalsIgnoreCase("student")){
Intent i = new Intent(Login.this, StudentHomePage.class);
startActivity(i);
}else if (ps.equalsIgnoreCase("tutor")){
Intent i = new Intent(Login.this, TutorHomePage.class);
startActivity(i);
}else{
Toast.makeText(Login.this,
"Wrong input. Please check again the email and password.", Toast.LENGTH_SHORT).show();
return;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
// ...
}
});
}
Create two child nodes from users. One for students and one for tutors.(Give both child values a value of true, otherwise firebase doesn't save the children.)
Have two registration buttons ..one for students and one for tutors. Registration for Tutor code.....
mRegistration.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString();
final String password = mPassword.getText().toString();
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(DriverLoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()){
Toast.makeText(TutorsLoginActivity.this, "Sign in error", Toast.LENGTH_SHORT).show();
}else{
String user_id= mAuth.getCurrentUser().getUid();
DatabaseReference current_user_db= FirebaseDatabase.getInstance().getReference().child("Users").child("Tutors").child(user_id);
current_user_db.setValue(true);
}
}
});
}
});
Do the same for the students. Just change the .child("Tutors") to .child("Students") This will give you UIDs for the two different groups. And you can do the same when logging in. I think this is a better way to proceed.

Categories

Resources