how to know if a specific value already exists in the database? - android

When the user logs in with their google account, I need to create a database user in my firebase with their email, if a user already exists with the same email, I don't need to create another one. I wrote something like this:
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if(firebaseAuth.getCurrentUser() != null){
String userGoogleEmail = firebaseAuth.getCurrentUser().getEmail();
databaseUser.orderByChild("userEmail").equalTo(userGoogleEmail);
Toast.makeText(Activity_log_in.this, "already have", Toast.LENGTH_LONG).show();
startActivity( new Intent(Activity_log_in.this, List.class));
}
}
};
But I need to check a condition, before the query, and I don't know how to do that

Consider doing the following:
databaseUser.orderByChild("userEmail").equalTo(userGoogleEmail).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getChildrenCount() == 0){
//Can create new user
}else{
//User already exists
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
}););
Hope that works!

Related

Finding if Email and/or Username existing in Firebase - Android

I'm new to Firebase and Android so please be easy with me here.
I'm trying to validate if the username and/or email already in the DB.
The problem is that once the code finds out there no user with that username, he go to addUser() function that adds the username to the Fire-base.
I tried reading around the Android Studio Development and I get the manage single check for either Email or Username but not both.
old code :
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(""+Username).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
// User name already exists.
Toast.makeText(MainActivity.this, "Username already found in DB, try different Username", Toast.LENGTH_SHORT).show();
etUsername.setText("");
etUsername.hasFocus();
} else {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Users").child(""+Email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Email already exists
Toast.makeText(MainActivity.this, "Email already found in DB, try different Email", Toast.LENGTH_SHORT).show();
etEmail.setText("");
etEmail.hasFocus();
}else{
// if here, mean all good
addUser(Username, Password, Fname, Phone, Lname, Email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Can someone help or direct me to an article that demonstrate 2 checks with Firebase?
edit: I found out that I need to first to orderByChild the index im searching at so I solved the Email part but the Username part is still tricky as I'm getting back an Object instead of a String and I can't convert it
New Code:
ref.equalTo(Username).addListenerForSingleValueEvent(new ValueEventListener() {
String check = (String)ref.equalTo(Username).toString();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Message","username is:"+check);
if(dataSnapshot.exists()){
Log.i("user","you check if user and got it, mean there is one in DB");
// User name already exists.
Toast.makeText(MainActivity.this, "Username already found in DB, try different Username", Toast.LENGTH_SHORT).show();
etUsername.setText("");
etUsername.hasFocus();
} else {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.orderByChild("Email").equalTo(Email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Email already exists
Toast.makeText(MainActivity.this, "Email already found in DB, try different Email", Toast.LENGTH_SHORT).show();
etEmail.setText("");
etEmail.hasFocus();
}else{
// if here, mean all good
addUser(Username, Password, Fname, Phone, Lname, Email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
So if mixing both of my codes you will get the result I wanted.
In order to check if a username is in the DB I used the first part of my code and for the Email the second one
Full code for check if username and/or Email is used in Fire-base
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.child(""+Username).addListenerForSingleValueEvent(new ValueEventListener() {
String check = (String)ref.equalTo(Username).toString();
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Message","username is:"+check);
if(dataSnapshot.exists()){
Log.i("user","you check if user and got it, mean there is one in DB");
// User name already exists.
Toast.makeText(MainActivity.this, "Username already found in DB, try different Username", Toast.LENGTH_SHORT).show();
etUsername.setText("");
etUsername.hasFocus();
} else {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.orderByChild("Email").equalTo(Email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
// Email already exists
Toast.makeText(MainActivity.this, "Email already found in DB, try different Email", Toast.LENGTH_SHORT).show();
etEmail.setText("");
etEmail.hasFocus();
}else{
// if here, mean all good
addUser(Username, Password, Fname, Phone, Lname, Email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if you have questions, feel free to ask :)

Fetch and Compare Key and Value from Firebase Realtime Database

I'm trying to make an app in which user store his Data. I've used user shared preferences to save user login details but still for security purpose, i made an activity(Verify Passcode Activity) that ask user Passcode to allow access on the data. Now i'm able to save, fetch and delete data. But in my Verify Passcode Activity, i just want to fetch that particular key and value where passcode is stored. I don't want to fetch complete data in Verify Passcode Activity.
Below is the code which i used to save passcode to database:-
databaseReference.child(uniqueID).setValue(passcode);
Below is the code i'm tried to fetch only passcode:-
dbreference.child(uniqueID).orderByChild("passcode").equalTo(pass).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(getApplicationContext(), "Data exist", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Data doesn't exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Here uniqueID is "abhishek88666kumar"and pass is a variable used for getText().
Here is the screenshot of my Firebase Database :-
Database Screenshot
Here is Verify Passcode Activity Screenshot:-
Please have a look at Database Screenshot and Verify Passcode Activity Screenshot.
Agenda:
getText() from textView inside activity.
getValue from firebase realtime database (only for current user. 'abhishek88666kumar' in our case).
compare if 1 and 2 are same or not. (If same then redirect to MainActivity else show error.)
Please tell me what i'm doing wrong.
Thanks to all for your help :) Your answer didn't worked for me but with the help of your answers and my few knowledge, I made a solution for my problem myself.
Here is the code that matches my requirement. This code is working exactly how I wanted.
dbreference = FirebaseDatabase.getInstance().getReference("passcodes");
Query query = dbreference.orderByKey().equalTo(currentUser); //current user is "abhishek88666kumar" in this case.
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String passcode = txtPasscode.getText().toString;//Passcode is 1234 in this case.
String fetchedValue = "";
for (DataSnapshot snap : dataSnapshot.getChildren()){
fetchedValue = (String) snap.getValue();
}
if (!passcode.equals(fetchedValue)){
Toast.makeText(getApplicationContext(), "Passcode doesn't match.", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Passcode matched.", Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(), "No passcode found for this user", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Assuming pass is a value like 1234, this line:
dbreference.child(uniqueID).orderByChild("passcode").equalTo(pass).addListenerForSingleValueEvent(...
Should be:
FirebaseDatabase.getInstance().getReference("passcodes").orderByValue().equalTo(pass).addListenerForSingleValueEvent(...
This way the DataSnapshot will contain all child nodes of passcodes that have the value 1234, i.e. "abhishek88666kumar" in your JSON sample.
Also be sure to study the documentation on sorting and filtering data.
This is the first way to compare firebase data.
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
passcode = editText.getText().toString();
Toast.makeText(getApplicationContext(), "Data :"+passcode, Toast.LENGTH_LONG).show();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("passcode");
Query applesQuery = ref.orderByValue().equalTo(passcode);
applesQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(getApplicationContext(), "Data exist", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Data doesn't exist"+passcode, Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}
});
This is the second way to compare firebase data.
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check = editText.getText().toString();
Toast.makeText(getApplicationContext(), "Data :"+check, Toast.LENGTH_LONG).show();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("passcode");
// Query applesQuery = ref.child("Customers").orderByChild("abhishek88666kumar").equalTo(passcode);
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if(map.get("abhishek88666kumar")!=null){
passcode = map.get("abhishek88666kumar").toString();
if (passcode.equals(check))
{
Toast.makeText(getApplicationContext(), "Data exist", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "Data doesn't exist"+check, Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Log.e(TAG, "onCancelled", databaseError.toException());
}
});
}
});
Both are working.
Hope it's help full for you.
thank you.

Check if email is existing on database

I'm trying to check if the user's email is existing in my Firebase Realtime Database. I used Firebase Authenticate to get user's Google Play Email, and if the user's email is not existing on my Firebase, the user will be prompted to another activity. Here's my code:
MainActivity.class
// Let's declare Firebase
private DatabaseReference mDatabase;
private FirebaseAuth mAuth;
private FirebaseUser mUser;
#Override
public void onStart() {
super.onStart();
// Check if user is signed in (non-null) and update UI accordingly.
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUser = mAuth.getInstance().getCurrentUser();
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String dEmail = dataSnapshot.getValue().toString();
String gEmail = mUser.getEmail();
for(DataSnapshot data: dataSnapshot.getChildren()){
if(data.child("email").child(EncodeString(gEmail)).exists()) {
Toast.makeText(getApplicationContext(), "There's one: " + EncodeString(gEmail), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "No email: " + EncodeString(gEmail), Toast.LENGTH_LONG).show();
}
}
/*
if(dEmail == gEmail) {
startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
finish();
} else {
Toast.makeText(getApplicationContext(), "No email", Toast.LENGTH_LONG).show();
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
public static String EncodeString(String string) {
return string.replace(".", ",");
}
public static String DecodeString(String string) {
return string.replace(",", ".");
}
Here's the structure of my Firebase Realtime Database
UPDATE: The question is how can I check if the email (the email is the one in my google play which is sholomon12#g..) is exisiting in my database. Note: I got the same email inserted, I just replaced the one in database with comma since I can't insert dot in firebase database
There is a workaround here when creating users in a Firebase database. Instead of using that random generated id provided by the push() method, use the email address. Your database structure should look like this:
Firebase-root
|
--- users
|
--- john#email,com
|
--- //user details
Now to check the users for existens, you can use exists() method on DatabaseReference object. So to chieve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference yourRef = rootRef.child("users").child("john#email,com");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
//do something
} else {
//do something else
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
yourRef.addListenerForSingleValueEvent(eventListener);

How to separate two different user in firebase android app?

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
}
// ...
}
};

ValueEventListener never being entered

I have a ValueEventListener, and the inner code is never being reached. My app is authenticating, but I can't retrieve data and I'm not sure what I'm missing. In the code below, when I check, uid has the correct value, and the data path ("Users/[uid]") is correct, but none of the inner code in the value event listener is never being reached. I've also tried to place a listener right at the root, with the same result.
I've set up Firebase using the menu options, adding both Authentication and Realtime Database to my app; authentication is working fine, so I'm wondering if there is something else that needs to be configured for the realtime database? I've read the documentation and walked through many examples but I can't see anything I'm missing.
uid = FirebaseAuth.getInstance().getCurrentUser().getUid().toString();
DatabaseReference userRef = ref.child("Users").child(uid).getRef();
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user == null) {
SettingsLoad();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("User", "User not found" );
}
};
userRef.addListenerForSingleValueEvent(userListener);
Try this!
I've just added else condition and log or toast the results!!
uid = FirebaseAuth.getInstance().getCurrentUser().getUid().toString();
DatabaseReference userRef = ref.child("Users").child(uid).getRef();
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
if (user == null) {
SettingsLoad();
}
**else {
Log.d("tag","User Found!");
}**
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("User", "User not found" );
}
};
userRef.addListenerForSingleValueEvent(userListener);

Categories

Resources