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 :)
Related
I've created String userenrollment that store user entered enrollment number into it! and My firebase real time database looks like .
and I tried one query but it directly goes to else block saying data doesn't exist!
ref = FirebaseDatabase.getInstance().getReference();
Query query = ref.child("Information").orderByChild("enrollment").equalTo(userenrollment);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull #NotNull DataSnapshot snapshot) {
if (snapshot.getChildrenCount()>0) {
Toast.makeText(loginstudentdemo.this, "User exist!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(loginstudentdemo.this, "User doesn't exist", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull #NotNull DatabaseError error) {
Toast.makeText(loginstudentdemo.this, "Database Error", Toast.LENGTH_SHORT).show();
}
});
I'm developing a reservation mobile app wherein when I click the checkAvailability, it will check if the data already exists in the database. My problem is that I don't know how to access since the key is randomly generated. There is a lot of similar questions to mine but no solutions has been working for me.
Firebase Database(Screenshot):
btnAvailability.setOnClickListener
btnAvailability.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0");
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String type = dataSnapshot.child("checkIn").getValue().toString();
String type2 = dataSnapshot.child("productName").getValue().toString();
if(type.equals(checkInTV.getText().toString()) && type2.equals(beach_name.getText().toString())) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
From the looks of it, you're trying to check of there is a child that has order/0 with a specific checkIn and productName under Requests. In your current data structure you can do that with:
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0");
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String type = snapshot.child("checkIn").getValue().toString();
String type2 = snapshot.child("productName").getValue().toString();
if(type.equals("Saturday, April 20, 2019") && type2.equals("The Mansion")) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException()
}
});
Differences from your code:
I have a loop inside onDataChange, since a query can have multiple results.
I hardcoded the date to rule out the problem being caused by the way you input the data in the text view.
I handle onCancelled, since ignoring errors is just a bad idea.
A more efficient way to accomplish the same is to have Firebase do part of the query, like this:
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0/checkIn").equalTo("Saturday, April 20, 2019");
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String type2 = snapshot.child("productName").getValue().toString();
if(type2.equals("The Mansion")) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException()
}
});
In here the change is:
I moved part of the check into the query, so that Firebase can perform that filter on the server. This means it has to download less data to the client, making it both faster and cheaper.
You'll still have to filter the second value client-side, since Firebase queries can only order/filter on one property. For more on this, see Query based on multiple where clauses in Firebase.
Note that you're querying double nested data. While you can get this to work for a specific order (orders/0 in this example), if you can have multiple orders in a request, Firebase won't be able to query across all of them.
For more on this and a solution, see: Firebase Query Double Nested
I'd also recommend reading my answers about modeling categories, because I have a feeling you'll need this soon: Firebase query if child of child contains a value
While storing data you need make user email id as first parameter so that you can access data based on user.
{"reuest":{"xyz#gmail.com":{"orders":[{"checkin":"21:29"},{"checkin":"2:19"}]},"abc#gmail.com":{"orders":[{"checkin":"21:29"},{"checkin":"2:19"}]}}}
Finally found a solution on my problem.
btnAvailability.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Query userQuery = database.getInstance().getReference().child("Requests")
.orderByChild("order/0/checkIn").equalTo(checkInTV.getText().toString());
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String type2 = snapshot.child("order/0/productName").getValue().toString();
if(type2.equals(beach_name.getText().toString())) {
Toast.makeText(details.this, "Not Available", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(details.this, "Available", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
});
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.
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);
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!