What I want to do for my Login page is log as user using email/password and when "role" is equal to flood victim (the other role is Rescuer and Admin). The Flood victim page is HomeActivity.class and the rescuer page is HomeRes.class.
Here is my code for loginActivity:
LoginAcitivty:
mAuth.signInWithEmailAndPassword(userEmail, userPswd)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
//Sign in success, update UI with the signed-in user's information
Toast.makeText(LoginActivity.this, "Login Successfull!",Toast.LENGTH_SHORT).show();
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference reference = firebaseDatabase.getReference().child("User");
//check if user has success registered
reference.orderByChild("userName").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
Log.d("User exists", "Welcome!");
String value = snapshot.child("userRole").getValue().toString();
if (value.equals("Flood Victim") && value != null) {
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
} else if (value.equals("Rescuer")) {
startActivity(new Intent(LoginActivity.this, homeRescuer.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this, homeFv.class));
finish();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}else {
// If sign in fails, display a message to the user.
Toast.makeText(LoginActivity.this, "Error" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
}
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your onDataChange needs to handle this list by looping over the children of the snapshot it gets.
reference.orderByChild("userName").equalTo(userEmail).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot: snapshot.getChildren()) { // 👈
String value = userSnapshot.child("userRole").getValue(String.class); // 👈
if ("Flood Victim".equals(value)) { // 👈
startActivity(new Intent(LoginActivity.this, HomeActivity.class));
finish();
} else if ("Rescuer".equals(value)) { // 👈
startActivity(new Intent(LoginActivity.this, homeRescuer.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this, homeFv.class));
finish();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // 👈 never ignore errors
}
});
Related
this is my code, and there is a problem in if statment, I need to make query about the user name if exist and then make a query to check if the user enter the password right or no
Query checkUser = FirebaseDatabase.getInstance().getReference("Users").orderByChild("fName").equalTo(inputName);
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
eName.setError(null);
eName.setEnabled(true);
if(snapshot.child(inputName).child("pass").getValue().equals(inputPassword)) {
ePassword.setError(null);
ePassword.setEnabled(true);
Toast.makeText(MainActivity.this, "Login was successful!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, HomePage.class);
startActivity(intent);
} else {
Toast.makeText(MainActivity.this, "Incorrect Password! ", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(MainActivity.this, "Incorrect Username! ",Toast.LENGTH_SHORT).show();
}
}
this is my screenshot for database
Your getting list of datasnapshot. So just retrieve the data snapshot from it and compare password.
checkUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapShot: dataSnapshot.getChildren()) {
if(userSnapShot.child("pass").getValue(String.class).equals(inputPassword)) {
Log.e("password", "Valid");
} else {
Toast.makeText(MainActivity.this, "Incorrect Password! ", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
Hello I am creating an app where there is two roles, admin and student.
The admin part is currently doing it's job and logging in the assigned activity.
I don't know how to separate the two roles using realtime database and using snapshot method.
So I added a field "isAdmin" and "isStudent" I was thinking to add at least a value. So everytime a user will login, it will see if the user has "isAdmin" and has value and will direct to other activity the same goes to "isStudent".
The thing now is that, i don't know how to do it, there's no snapshot.hasChild("isAdmin").equals("1") or stuff. The only thing I need is that, the user will be logged in if the account has a field of "isAdmin"/"isStudent" and has value.
here's my code in login part.
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkField(userID);
checkField(password);
if(valid){
mAuth.signInWithEmailAndPassword(userID.getText().toString() +"#gmail.com".trim(), password.getText().toString().trim()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Toast.makeText(LoginActivity.this, "Logged in Successfully", Toast.LENGTH_SHORT).show();
CheckUserAccessLevel(authResult.getUser().getUid());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
});
so basically I am calling a function CheckUserAccessLevel wherein it filters the users role.
So this is my CheckUserAccessLevel function... But it only intents the Admin Account but not the Student Account
private void CheckUserAccessLevel(String uid) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users/"+uid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.hasChild("isAdmin")){
Toast.makeText(LoginActivity.this, "Logged in as Admin", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), WelcomeAdminActivity.class));
finish();
}
else if (snapshot.hasChild("isStudent")){
Toast.makeText(LoginActivity.this, "Logged in as Student", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), WelcomeStudentActivity.class));
finish();
}
else {
FirebaseAuth.getInstance().signOut();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
finish();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(LoginActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
this is my realtime database
I'm doing a project called e-school. It has 4 types of users which uses Firebase authentication and Firebase realtime database to login to their accounts, Anyway, I'm getting issues while working with Firebase realtime database and Firebase authentication. I'm letting users to their respective dashboards comparing the authentication data with the realtime database.
//Registration Code
auth.createUserWithEmailAndPassword(email.getText().toString(), password.getText().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Users user = new Users();
user.setE_mail(email.getText().toString());
user.setNumber(Phone.getText().toString());
user.setPassword(password.getText().toString());
user.setU_name(username.getText().toString());
users.child("principal").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.setValue(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Snackbar.make(rootLayout, "Registration Success",Snackbar.LENGTH_LONG)
.show();
return;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(rootLayout, "Registration Failed: "+e.getMessage(), Snackbar.LENGTH_LONG)
.show();
return;
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(rootLayout, "Failed :"+e.getMessage(),Snackbar.LENGTH_LONG)
.show();
return;
}
});
}
});
//Login COde
auth.signInWithEmailAndPassword(t_email.getText().toString(), t_password.getText().toString())
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
id = auth.getUid();
teacherValidation(id);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Snackbar.make(rootLayout,"Authentication Failed", Snackbar.LENGTH_SHORT).show();
}
});
//TeacherValidate
private void teacherValidation(final String id) {
users = db.getInstance().getReference("Users/teachers");
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.getKey().equals(id)){
Toast.makeText(MainActivity.this," "+id,Toast.LENGTH_SHORT).show();
Intent it = new Intent(MainActivity.this, teachers.class);
it.putExtra("UID", id);
startActivity(it);
finish();
}else{
Toast.makeText(MainActivity.this, "No Teacher Esxist With the Given Credientialss", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
It is not necessary to get all teachers details on client side. Instead you can directly check in database for that user, it'll increase the performance of app also.
Just modify teacherValidation method like this.
private void teacherValidation(final String id) {
users = db.getInstance().getReference("Users/teachers").child(id);
users. addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// If below condition checks true,
// that means user exists on teacher node, so probably he/she is a teacher.
if(dataSnapshot.getValue() != null){
Toast.makeText(MainActivity.this," "+id,Toast.LENGTH_SHORT).show();
Intent it = new Intent(MainActivity.this, teachers.class);
it.putExtra("UID", id);
startActivity(it);
finish();
}else{
Toast.makeText(MainActivity.this, "No Teacher Exist With the Given Credientialss", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
I got this code snippet. Probably addListenerForSingleValueEvent is your method.
Pay special attention in the way the query is built, calling a first child which is the table called "users" and then a second child which is a user with a specific userId. FUser is equivalent to your Users class.
Try it...
private void getFirebaseUserInfo(final String userId, final GetUserInfoListener userInfoListener) {
DatabaseReference userIdReference = getDatabaseReference().child("users").child(userId);
userIdReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
try {
final Users user = dataSnapshot.getValue(FUser.class);
if (!user.email.isEmpty()) {
// Do whatever
} else {
userInfoListener.onSuccess(user);
}
} catch(DatabaseException e) {
userInfoListener.onFailure(new Exception(e.getMessage()));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
userInfoListener.onFailure(new Exception(databaseError.getMessage()));
}
});
}
Also, look at the difference:
Difference between addValueEventListener() and addListenerForSingleValueEvent() of firebase
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 have two user type. After destroy app I want to go to two activity for two user type. With my method I cant access current user because user is not logined
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
if(loginflag.equals("0")){
startActivity(new Intent(LoginActivity.this, HomeUsers.class));
finish();
}
else if (loginflag.equals("1")) {
startActivity(new Intent(LoginActivity.this, HomeEducator.class));
finish();
}
}
}
private void loginControl() {
FirebaseUser user = auth.getCurrentUser();
String id = user.getUid();
DatabaseReference FirebaseRef = FirebaseDatabase.getInstance().getReference().child("users").child(id);
FirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if(snapshot.exists()){
loginflag = snapshot.child("flag").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Can you try this
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
String id = auth.getCurrentUser().getUid();
DatabaseReference FirebaseRef = FirebaseDatabase.getInstance().getReference().child("users").child(id);
FirebaseRef.child("flag").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()) {
String loginflag = snapshot.getValue().toString();
if (loginflag.equals("0")) {
startActivity(new Intent(LoginActivity.this, HomeUsers.class));
finish();
} else if (loginflag.equals("1")) {
startActivity(new Intent(LoginActivity.this, HomeEducator.class));
finish();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
To solve this, you need to add under each user inside your database a flag named userType. Then when the users is loggin in, check what kind of user is, to know to which activity you need to redirect it. The logic should be as follows:
if(userModel.getUserType().equals("homeUser")) {
startActivity(new Intent(LoginActivity.this, HomeUsers.class));
finish();
} else if (userModel.getUserType().equals("homeEducator")) {
startActivity(new Intent(LoginActivity.this, HomeEducator.class));
finish();
}